Java 布尔值和 NULL 的处理
Java handling of Boolean and NULL
JAVA 中的布尔对象可以有 3 个值 True、False、NULL
public class First {
public static void main(String args[])
{
System.out.println("equals(new Boolean(\"True\"),True) :: " + isEqual(new Boolean("True"), true));
System.out.println("equals(new Boolean(\"False\"), new Boolean(null)) :: " + isEqual(new Boolean("False"), new Boolean(null)));
System.out.println("equals(new Boolean(\"False\"), null)) :: " + isEqual(new Boolean("False"), null));
}
static boolean isEqual(Boolean a, Boolean b)
{
return a.equals(b);
}
}
以上代码的输出是
equals(new Boolean("True"),True) :: true
equals(new Boolean("False"), new Boolean(null)) :: true
equals(new Boolean("False"), null)) :: false
请解释为什么案例 2 returns 正确但案例 3 returns 错误
如果你查看 Boolean
class 的源代码,你可以看到传递一个 null
值 returns false
:
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
这是因为 Boolean
的构造函数,如果提供 null
将分配一个表示值 false
的布尔对象
阅读此处:http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
public Boolean(String s)
Allocates a Boolean object representing the value true if the string
argument is not null and is equal, ignoring case, to the string
"true". Otherwise, allocate a Boolean object representing the value
false. Examples: new Boolean("True") produces a Boolean object that
represents true. new Boolean("yes") produces a Boolean object that
represents false. Parameters:s - the string to be converted to a
Boolean.
JAVA 中的布尔对象可以有 3 个值 True、False、NULL
public class First {
public static void main(String args[])
{
System.out.println("equals(new Boolean(\"True\"),True) :: " + isEqual(new Boolean("True"), true));
System.out.println("equals(new Boolean(\"False\"), new Boolean(null)) :: " + isEqual(new Boolean("False"), new Boolean(null)));
System.out.println("equals(new Boolean(\"False\"), null)) :: " + isEqual(new Boolean("False"), null));
}
static boolean isEqual(Boolean a, Boolean b)
{
return a.equals(b);
}
}
以上代码的输出是
equals(new Boolean("True"),True) :: true
equals(new Boolean("False"), new Boolean(null)) :: true
equals(new Boolean("False"), null)) :: false
请解释为什么案例 2 returns 正确但案例 3 returns 错误
如果你查看 Boolean
class 的源代码,你可以看到传递一个 null
值 returns false
:
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
这是因为 Boolean
的构造函数,如果提供 null
将分配一个表示值 false
阅读此处:http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
public Boolean(String s)
Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false. Examples: new Boolean("True") produces a Boolean object that represents true. new Boolean("yes") produces a Boolean object that represents false. Parameters:s - the string to be converted to a Boolean.