java – 为什么返回null(需要布尔值)作为三元运算符编译的结果?

参见英文答案 > 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.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...