Java, comparing BigInteger values

前端 未结 3 1249
囚心锁ツ
囚心锁ツ 2021-02-05 05:25
BigInteger bigInteger = ...;


if(bigInteger.longValue() > 0) {  //original code
    //bigger than 0
}

//should I change to this?
if(bigInteger.compareTo(BigInteger.         


        
3条回答
  •  春和景丽
    2021-02-05 05:35

    This is not a direct answer, but an important note about using compareTo().

    When checking the value of compareTo(), always test for x < 0, x > 0 and x == 0.
    Do not test for x == 1

    From the Comparable.compareTo() javadocs:

    Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

    Note:

    • A negative integer, not -1.
    • A positive integer, not 1.

    True, checking for ==1 and ==-1 would work for BigInteger. This is the BigInteger.compareTo() code:

    public int compareTo(BigInteger val) {
        if (signum == val.signum) {
            switch (signum) {
            case 1:
                return compareMagnitude(val);
            case -1:
                return val.compareMagnitude(this);
            default:
                return 0;
            }
        }
        return signum > val.signum ? 1 : -1;
    }
    

    But it's still bad practice, and explicitly recommended against in the JavaDocs:

    Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.

提交回复
热议问题