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

后端 未结 4 1337
执笔经年
执笔经年 2021-02-08 08:51

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

<         


        
4条回答
  •  面向向阳花
    2021-02-08 09:33

    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.

提交回复
热议问题