gpt4 book ai didi

Java boolean 值和 NULL 的处理

转载 作者:行者123 更新时间:2023-12-02 15:15:23 24 4
gpt4 key购买 nike

JAVA中的 boolean 对象可以有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 返回 true 而情况 3 返回 false

最佳答案

这是因为 Boolean 的构造函数如果提供 null 将分配一个表示值 false 的 Boolean 对象

阅读此处: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 boolean 值和 NULL 的处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com