java:三元运算符(?:)中的NullPointerException很奇怪 [英] java: weird NullPointerException in ternary operator (? : )

查看:94
本文介绍了java:三元运算符(?:)中的NullPointerException很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

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 ,则取消装箱的NPE。

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很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆