比较 Java 布尔类
我惊讶地发现用 == 比较两个布尔对象可能会得到错误的答案。
看下面的测试代码。测试 a 和测试 c 给出了一致的答案。
测试 b 失败。看来new Boolean(true)可以创建一个具有相同值的单独对象,而不是返回对Boolean.TRUE的引用;
public static void main(String[] args) {
Boolean a = Boolean.TRUE;
Boolean b = new Boolean(true);
Boolean c = null;
boolean x = true;
boolean y = false;
System.out.println("Test a");
System.out.println(( a == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(a)) ? "TRUE" : "FALSE");
System.out.println("Test b");
System.out.println(( b == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(b)) ? "TRUE" : "FALSE");
System.out.println("Test c");
System.out.println(( c == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(c)) ? "TRUE" : "FALSE");
/* OUTPUT is
Test a
TRUE
TRUE
Test b
FALSE
TRUE
Test c
FALSE
FALSE
*/
}
I was stunned to learn that comparing two Boolean Objects with == can get the wrong answer.
Look at the test code below. Test a and Test c give consistent answers.
Test b fails. It seems that new Boolean(true) can create a separate object with the same value, instead of returning a reference to Boolean.TRUE;
public static void main(String[] args) {
Boolean a = Boolean.TRUE;
Boolean b = new Boolean(true);
Boolean c = null;
boolean x = true;
boolean y = false;
System.out.println("Test a");
System.out.println(( a == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(a)) ? "TRUE" : "FALSE");
System.out.println("Test b");
System.out.println(( b == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(b)) ? "TRUE" : "FALSE");
System.out.println("Test c");
System.out.println(( c == Boolean.TRUE ) ? "TRUE" : "FALSE");
System.out.println(( Boolean.TRUE.equals(c)) ? "TRUE" : "FALSE");
/* OUTPUT is
Test a
TRUE
TRUE
Test b
FALSE
TRUE
Test c
FALSE
FALSE
*/
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
Boolean
是一个引用类型,并且==
测试它们是否是内存中的同一个对象,那么你会得到 false,因为你用分配了
b
>新。Because
Boolean
is a reference type and==
tests if they are the same object in memory then you get false because you allocatedb
withnew
.