问题描述
请考虑以下代码片段:
private static void doSomething(Double avg, Double min, Double sd) {
final Double testMin;
if (avg != null) {
testMin = Math.max(min, avg - 3 * sd);
} else {
testMin = min;
}
System.out.println("testMin=" + testMin);
final Double verwachtMin = avg != null ? Math.max(min, avg - 3 * sd) : min;
System.out.println("verwachtMin=" + verwachtMin);
}
据我所知(以及我的 IDE 可以告诉我什么),变量 testMin
和 verwachtMin
应该是等效的.
As far as I know (and for what my IDE can tell me), the variables testMin
and verwachtMin
should be equivalent.
如您所料,我宁愿写最后 2 行而不是前 7 行.但是,当我向此方法传递 3 个空值时,我在计算 verwachtMin
变量.
As you might expect, I'd rather write the last 2 lines than the first 7. However, when I pass 3 null values to this method, I get an NPE on the calculation of the verwachtMin
variable.
有谁知道这是怎么发生的?三元运算符是否计算第二部分,即使条件不是 true
?
Does anyone know how this can happen? Does the ternary operator evaluate the 2nd part, even when the condition is not true
?
(Java 版本 1.6.0_21)
(Java version 1.6.0_21)
推荐答案
尝试:
final Double verwachtMin = avg != null ? new Double(Math.max(min, avg - 3 * sd)) : min;
或
final Double verwachtMin = avg != null ? Double.valueOf(Math.max(min, avg - 3 * sd)) : min;
三元运算符的交替边的类型是double
和Double
,这意味着Double
被拆箱为double
,然后在赋值时我们有一个从 double
到 Double
的装箱.如果 min
的值为 null
那么拆箱 NPEs.
The types of the alternate sides of the ternary operator were double
and Double
, which means that the Double
gets unboxed to double
, and then on assignment we have a boxing from double
to Double
. If the value of min
is null
then the unboxing NPEs.
这篇关于java:三元运算符(?:)中的奇怪的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!