java Boolean.TRUE == myBoolean vs. Boolean.TRUE.equals(myBoolean)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16437236/
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
Boolean.TRUE == myBoolean vs. Boolean.TRUE.equals(myBoolean)
提问by Edd
Is there ever a situation where using equals(Boolean)and ==would return different results when dealing with Booleanobjects?
在处理对象时,是否存在使用equals(Boolean)和==会返回不同结果的情况Boolean?
Boolean.TRUE == myBoolean;
Boolean.TRUE.equals(myBoolean);
I'm not thinking about primitive types here, just Boolean objects.
我不是在这里考虑原始类型,只是 Boolean 对象。
采纳答案by assylias
How about:
怎么样:
System.out.println(new Boolean(true) == new Boolean(true));
System.out.println(new Boolean(true) == Boolean.TRUE);
(both print false, for the same reason as any other type of objects).
(两者都打印 false,原因与任何其他类型的对象相同)。
回答by Marko Topolnik
It would be dangerous to use ==because myBooleanmay not have originated from one of the constants, but have been constructed as new Boolean(boolValue), in which case ==would always result in false. You can use just
使用它会很危险,==因为myBoolean可能不是源自其中一个常量,而是被构造为new Boolean(boolValue),在这种情况下==总是会导致false. 你可以只使用
myBoolean.booleanValue()
with neither ==nor equalsinvolved, giving reliable results. If you must cater for null-values as well, then there's nothing better than your equalsapproach.
既不参与==也不equals参与,给出可靠的结果。如果您还必须满足null-values 的需求,那么没有什么比您的equals方法更好的了。
回答by Vineet Singla
if (Boolean.TRUE == new Boolean(true)) {
System.out.println("==");
}
if (Boolean.TRUE.equals(myBoolean)) {
System.out.println("equals");
}
In this case first one is false. Only second if condition is true.
在这种情况下,第一个是错误的。如果条件为真,则仅第二个。
It Prints:
它打印:
equals
等于
回答by Kuchi
==only works for primitive types
when you compare Objects you should always use o.equls(Object ob)
==
当您比较应该始终使用的对象时,仅适用于原始类型o.equls(Object ob)

