比较 Java 布尔类

发布于 2024-12-26 16:53:55 字数 989 浏览 1 评论 0原文

我惊讶地发现用 == 比较两个布尔对象可能会得到错误的答案。

看下面的测试代码。测试 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿嘿嘿 2025-01-02 16:53:55

因为 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 allocated b with new.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文