如果我使用三元运算符,我会得到空指针异常。
Integer val = null;
Object res = val == null ? val : val.intValue();
但不是 if else
Integer val = null;
Object res;
if( val == null ) {
res = val;
} else {
res = val.intValue();
}
谁能解释一下为什么?
谢谢
苏达尔
您遇到的行为源于确定三元条件表达式类型的规则。
在你的例子中,表达式的类型
val == null ? val : val.intValue();
是int
。
这由 JLS 15.25. 指定:
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.
第二个操作数是Integer
,第三个操作数是int
,因此表达式的类型是int
。
因此,当 val == null 时,val
被拆箱(即 val.intValue()
被调用以获得 null 值)和 NullPointerException
被抛出。
在你的 if-else 表达式中 val
当它的值为 null 时不会被拆箱(因为你将它分配给一个 Object
变量,所以没有 空指针异常
。
也就是说,由于您将一个 Integer 变量分配给一个 Object 变量,所以您在任何一个片段中的条件都是毫无意义的(因为将一个 int
分配给一个 Object
变量简单地将 int
装回 Integer
)。
你可以简单地赋值
Object res = val;
并毫无异常(exception)地得到相同的最终结果。