Possible Duplicates:
Booleans, conditional operators and autoboxing
Java, Google Collections Library; problem with AbstractIterator?
下面的代码产生一个 NPE:
Integer test = null;
Integer test2 = true ? test : 0;
System.out.println(test2);
要正确无一异常(exception)地打印出“null”,需要以下代码:
Integer test = null;
Integer test2 = true ? test : (Integer)0;
System.out.println(test2);
在第一个示例中很明显“test”被拆箱(转换为 native int),但为什么呢?为什么改变三元运算符中的另一个表达式(如第二个示例)修复它?任何人都可以提供某种形式的叙述,说明这两个示例中的内容何时、何地以及为何被装箱和拆箱?
来自 section 15.25 of the Java Language Specification :
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 type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean.
- If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
- Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
- If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the conditional expression is short.
- If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
- If one of the operands is of type Byte and the other operand is a constant expression of type int whose value is representable in type byte, then the type of the conditional expression is byte.
- If one of the operands is of type Short and the other operand is a constant expression of type int whose value is representable in type short, then the type of the conditional expression is short.
- If one of the operands is of type; Character and the other operand is a constant expression of type int whose value is representable in type char, then the type of the conditional expression is char.
- Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).
所以它紧跟最后一个项目符号,执行二进制数字提升,执行拆箱转换。所以条件运算符表达式的类型是 int
,即使您将它分配给 Integer
。它试图对 null
执行拆箱转换,因此出现异常。