java 如何检查 BigInteger 是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31072498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a BigInteger is null
提问by gnsb
I have a code which may assign null to a BigInteger. I need to check if it is null or not.
我有一个代码可以将 null 分配给 BigInteger。我需要检查它是否为空。
I've tried the following things, and they do not work:
我尝试了以下事情,但它们不起作用:
==
will just check the reference, not the value.BigInteger x = BigInteger.ONE; if(x== null) { System.out.println( x ); }
==
只会检查引用,而不是值。BigInteger x = BigInteger.ONE; if(x== null) { System.out.println( x ); }
Output of above is it prints x. (Somehow the boolean condition is satisfied, even though x is not null).
上面的输出是打印 x。(以某种方式满足布尔条件,即使 x 不为空)。
Following gives NullPointerException upon comparing
BigInteger x = BigInteger.ONE; BigInteger myNull = null; if(x.compareTo(myNull) == 0 ) { System.out.println( x ); }
Another NPE:
BigInteger x = BigInteger.ONE; if(x.compareTo(null) == 0) { System.out.println( x ); }
以下在比较时给出 NullPointerException
BigInteger x = BigInteger.ONE; BigInteger myNull = null; if(x.compareTo(myNull) == 0 ) { System.out.println( x ); }
另一个 NPE:
BigInteger x = BigInteger.ONE; if(x.compareTo(null) == 0) { System.out.println( x ); }
How do I check if a BigInteger is null properly?
如何检查 BigInteger 是否正确为空?
回答by Robin Krahl
There is a difference between a null
reference and an object with the value 0. To check for null
references, use:
null
引用和值为 0 的对象之间存在差异。要检查null
引用,请使用:
BigInteger value = getValue();
if (value != null) {
// do something
}
To check for the value 0, use:
要检查值 0,请使用:
BigInteger value = getValue();
if (!BigInteger.ZERO.equals(value)) {
// do something
}
To ensure the object is neither a null
reference nor has the value 0, combine both:
为确保对象既不是null
引用也不是值 0,请将两者结合起来:
BigInteger value = getValue();
if (value != null && !value.equals(BigInteger.ZERO)) {
// do something
}
2015-06-26: Edited according to @Arpit's comment.
2015-06-26:根据@Arpit 的评论进行编辑。
回答by Bathsheba
.compareTo(arg)
throws a NullPointerException if arg
is null
.
.compareTo(arg)
如果arg
是,则抛出 NullPointerException null
。
You should check if arg
is null
prior to calling the method.
您应该检查是否arg
是null
之前调用该方法。