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

拥有回忆 提交于 2020-01-12 07:38:15

问题


Is there ever a situation where using equals(Boolean) and == would return different results when dealing with Boolean objects?

Boolean.TRUE == myBoolean;

Boolean.TRUE.equals(myBoolean);

I'm not thinking about primitive types here, just Boolean objects.


回答1:


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).




回答2:


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. You can use just

myBoolean.booleanValue()

with neither == nor equals involved, giving reliable results. If you must cater for null-values as well, then there's nothing better than your equals approach.




回答3:


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




回答4:


== only works for primitive types
when you compare Objects you should always use o.equls(Object ob)



来源:https://stackoverflow.com/questions/16437236/boolean-true-myboolean-vs-boolean-true-equalsmyboolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!