为什么这段代码有效?
Float testFloat = null;
Float f = true ? null : 0f;
为什么这会抛出异常?
Float testFloat = null;
Float f = true ? testFloat : 0f;
但最奇怪的是,这段代码也运行成功,没有任何异常:
Float testFloat = null;
Float f = testFloat;
看来 Java 的三元运算符改变了行为。谁能解释一下这是为什么吗?
该行为在中指定JLS - 条件运算符:
如果第二个和第三个操作数之一是原始类型 T,而另一个的类型是对 T 应用装箱转换(第 5.1.7 节)的结果,则条件表达式的类型为 T.
Emphasis mine. So, in the 2nd case:
Float f = true ? testFloat : 0f;
由于第三个操作数是原始类型(T
),表达式的类型将是 float 类型 -T
. So, unboxing 测试浮动目前是一个null
参考,至float
将导致NPE.
As for the 1st case, relevant part is the last one:
否则,第二和第三操作数分别是类型S1和S2。令 T1 为对 S1 应用装箱转换所产生的类型,并令 T2 为对 S2 应用装箱转换所产生的类型。条件表达式的类型是将捕获转换 (§5.1.10) 应用于 lub(T1, T2) (§15.12.2.7) 的结果。
所以,根据这个:
null type - S1
float - S2
null type - T1 (boxing null type gives null type)
Float - T2 (float boxed to Float)
然后条件表达式的类型变为 -Float
。没有拆箱null
需要,因此没有NPE
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)