简体   繁体   English

Boolean.TRUE == myBoolean与Boolean.TRUE.equals(myBoolean)

[英]Boolean.TRUE == myBoolean vs. Boolean.TRUE.equals(myBoolean)

Is there ever a situation where using equals(Boolean) and == would return different results when dealing with Boolean objects? 在处理Boolean对象时,是否存在使用equals(Boolean)==会返回不同结果的情况?

Boolean.TRUE == myBoolean;

Boolean.TRUE.equals(myBoolean);

I'm not thinking about primitive types here, just Boolean objects. 我不是在考虑原始类型,只是布尔对象。

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, 原因与任何其他类型的对象相同 )。

It would be dangerous to use == because myBoolean may not have originated from one of the constants, but have been constructed as new Boolean(boolValue) , in which case == would always result in false . 使用==会很危险,因为myBoolean可能不是源于其中一个常量,而是构造为new Boolean(boolValue) ,在这种情况下==总是会导致false You can use just 你可以使用

myBoolean.booleanValue()

with neither == nor equals involved, giving reliable results. 既没有==也没有equals ,给出了可靠的结果。 If you must cater for null -values as well, then there's nothing better than your equals approach. 如果你也必须满足null ,那么没有比你的equals方法更好的了。

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 等于

== only works for primitive types ==仅适用于原始类型
when you compare Objects you should always use o.equls(Object ob) 比较对象时,应始终使用o.equls(Object ob)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM