如何检查BigInteger是否为null

gns*_*nsb -3 java biginteger compareto

我有一个代码可以为BigInteger分配null.我需要检查它是否为空.

我尝试过以下的东西,它们不起作用:

  1. == 只会检查参考,而不是值.

    BigInteger x = BigInteger.ONE;
    
    if(x== null)
    {
        System.out.println( x );
    }
    
    Run Code Online (Sandbox Code Playgroud)

以上输出是打印x.(不管怎样,布尔条件都满足,即使x不为null).

  1. 以下在比较时给出NullPointerException

    BigInteger x = BigInteger.ONE;
    BigInteger myNull = null;
    
    if(x.compareTo(myNull) == 0 )
    {
        System.out.println( x );
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 另一个NPE:

    BigInteger x = BigInteger.ONE;
    
    if(x.compareTo(null) == 0)
    {
        System.out.println( x );
    }
    
    Run Code Online (Sandbox Code Playgroud)

如何检查BigInteger是否正确?

Rob*_*ahl 6

null引用和值为0的对象之间存在差异.要检查null引用,请使用:

BigInteger value = getValue();
if (value != null) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

要检查值0,请使用:

BigInteger value = getValue();
if (!BigInteger.ZERO.equals(value)) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

要确保对象既不是null引用也不是值0,请将两者结合使用:

BigInteger value = getValue();
if (value != null && !value.equals(BigInteger.ZERO)) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

2015-06-26:根据@ Arpit的评论编辑.