有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java,比较大整数值

BigInteger bigInteger = ...;


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

//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
    //bigger than 0
}

我需要比较一些任意的大整数值。我不知道哪种方法是正确的。鉴于上述代码,应使用哪种代码?原始代码在顶部。。我想把它改成第二种方法


共 (3) 个答案

  1. # 1 楼答案

    如果您使用的是BigInteger,则假定您需要的数字大于long所能处理的数字。所以不要使用longValue()。使用compareTo。以你的例子来说,最好是:

    if (bigInteger.compareTo(BigInteger.ZERO) > 0) {
    
    }
    
  2. # 2 楼答案

    这不是一个直接的答案,而是关于使用compareTo()的一个重要注意事项

    检查compareTo()的值时,始终测试x < 0x > 0x == 0
    不要测试x == 1

    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.

    注:

    • A negative integer,而不是{}
    • A positive integer,而不是{}

    如果为True,则检查==1==-1将适用于BigInteger。这是BigInteger.compareTo()代码:

    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;
    }
    

    但这仍然是不好的做法,在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) <op> 0), where <op> is one of the six comparison operators.

  3. # 3 楼答案

    如果要测试BigInteger是否具有正值,则第一种方法是错误的:longValue只返回可能还原符号的低阶64位。。。因此,对于正的BigInteger,测试可能会失败

    第二种方法更好(参见Bozhos answer了解优化)

    另一种选择:BigInteger#signum如果值为正值,则返回1

    if (bigInteger.signum() == 1) {
     // bigger than 0
    }