当我尝试使用此代码时,我在Eclipse上遇到错误
boolean notif = (Boolean) null;
if(notif == null) // <== ERROR at this line saying "No suggestion available" (very helpful)
{
System.out.println("Notif = null");
}
为什么它不起作用?
答案 0 :(得分:6)
boolean
是原始类型,只接受true
或false
。如果您想将null
分配给您的变量,请改用对象Boolean
。
Boolean notif = null;
if(notif == null) {
System.out.println("Notif = null");
}
但是......如果您使用原始类型,请执行以下操作:
boolean notif = // true or false;
if(notif) {
System.out.println("Notif = true");
}
else {
System.out.println("Notif = false");
}
编辑: Boolean
和boolean
之间的区别在于第一个是对象,它带有一些您可能想要使用的方法。第二个,作为原始类型使用较少的内存。现在考虑这些点并选择你需要的东西;)
有关文档的Boolean
对象here的详情。
答案 1 :(得分:2)
布尔值不能为空。它可以是真的也可以是假的
boolean notif = false;
if(notif)
{
System.out.println("notif is true");
}
else
{
System.out.println("notif is false");
}
而对象Boolean
可以是。
答案 2 :(得分:2)
当你将null转换为&#34; Boolean时,它的包装类不是原始布尔值。但是当你进行比较时,你要与原始的布尔值进行比较,它只需要值为true或false,而不是null。
答案 3 :(得分:2)
您正尝试在原始数据类型中获取所有null的值, 相反,您应该使用布尔类,该类可以为null并且适合您的实现类型。
Boolean notif = null;
if( notif == null ) {
System.out.println("notif is null");
} else {
if(notif){
System.out.println("notif is true");
} else {
System.out.println("notif is false");
}
}