2017-02-21 108 views
0

我只是写了代码:JAVA布尔构造函数给出意想不到的结果

Boolean b1 = new Boolean("programmer"); 
Boolean b2 = new Boolean("tester"); 
System.out.println(b1.equals(b2)); 

它打印true作为输出中。 为什么?

根据JAVA文档

new Boolean(String):分配一个表示值真布尔对象如果字符串参数不是null和是相等的,忽略 情况下,将字符串“真”。

+1

这两个布尔人都是假的,因此他们是平等的,你的等号检查会打印出真实的。这里没有什么意外的。 –

+1

请仔细阅读最后一句。它给你的理由。 – Guy

+1

因为“如果字符串参数不为空并且等于(忽略大小写)为字符串”true“,则分配表示值为true的布尔对象。”其他任何东西都是假的。 –

回答

5
Boolean b1 = new Boolean("programmer"); // false 
Boolean b2 = new Boolean("tester"); // false 

因此测试false == falsetrue


public Boolean(String s) constructor signature

  • Boolean.parseBoolean("True")回报true

  • Boolean.parseBoolean("yes")回报false

  • 布尔
3

无论您b1b2Boolean.FALSE,因此他们是平等的。

只有字符串为"true"(忽略大小写)new Boolean(String)TRUE

下面是Boolean构造:

public Boolean(String s) { 
     this(parseBoolean(s)); 
    } 

而且parseBoolean方法:

public static boolean parseBoolean(String s) { 
    return ((s != null) && s.equalsIgnoreCase("true")); 
} 
1

默认值为false ..和你的情况

Boolean b1 = new Boolean("programmer"); // false 
System.out.println(b1); 
Boolean b2 = new Boolean("tester"); // false 
System.out.println(b2); 

所以false == false总是返回true

除此之外,如果你想比较,你有串给定,那么你应该使用String包装类。

相关问题