参见英文答案 >
Booleans,conditional operators and autoboxing4个
我刚刚注意到的一种好奇心,而不是一个问题.
我刚刚注意到的一种好奇心,而不是一个问题.
我不被允许写
public boolean x() { return null; }
或这个:
public boolean x() { if (DEBUG) { return true; } else { return null; } }
但我被允许写
public boolean x() { return DEBUG ? true : null; }
为什么是这样? (如果采用“else”分支,它似乎会抛出NPE.)
解决方法
正如
jls所述:
The type of a conditional expression is determined as follows:
If the second and third operands have the same type (which may be the null type),then that is the type of the conditional expression.
If one of the second and third operands is of primitive type T,and the type of the other is the result of applying Boxing conversion (§5.1.7) to T,then the type of the conditional expression is T.
这意味着java允许null,因为它可以用于生成Boolean的实例,可以将其解包为boolean(有关更多信息,请阅读jls中有关boxing的部分).但由于Boolean实例初始化为null,因此对booleanValue()的调用将导致NullPointerException.