三元运算符中不需要的 NullPointerException - 为什么? [英] Unwanted NullPointerException in ternary operator - Why?

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

问题描述

在执行以下代码时,我在行中收到 NullPointerException:

While executing the following code, I am getting a NullPointerException at line:

value = condition ? getDouble() : 1.0;

在前面几行中,当我使用 null 而不是 getDouble() 时,一切正常,这很奇怪.

In earlier lines when I use null instead of getDouble() everything works and this is strange.

public class Test {
    static Double getDouble() {
        return null;
    }

    public static void main(String[] args) {
        boolean condition = true;
        Double value;

        value = condition ? null : 1.0;         //works fine
        System.out.println(value);              //prints null

        value = condition ? getDouble() : 1.0;  //throws NPE
        System.out.println(value);
    }
}

有人能帮我理解这种行为吗?

Can someone help me understand this behavior?

推荐答案

当你写作时

value = condition ? null : 1.0;

条件的类型?null : 1.0 必须是引用类型,所以类型是Double,可以保存值null.

the type of condition ? null : 1.0 must be a reference type, so the type is Double, which can hold the value null.

写作时

value = condition ? getDouble() : 1.0;

getDouble()返回null,相当于写:

value = condition ? ((Double) null) : 1.0;

在这种情况下,编译器将 Doubledouble 视为三元条件运算符的第二个和第三个参数,并决定表达式的类型应该是 <代码>双.因此,它将 null 拆箱为 double,得到 NullPointerException.

In this case the compiler sees a Double and a double as the 2nd and 3rd arguments of the ternary conditional operator, and decides that type of the expression should be double. Therefore it unboxes the null to double, getting NullPointerException.

条件三元运算符的类型由JLS 15.25.

The type of the conditional ternary operator is determined by some tables in JLS 15.25.

如果第二个和第三个操作数是nulldouble,条件表达式类型是Double的最小上界null,即Double.

If the 2nd and 3rd operands are null and double, the conditional expression type is the least upper bound of Double and null, which is Double.

如果第二个和第三个操作数是Doubledouble,则条件表达式类型为double.

If the 2nd and 3rd operands are Double and double, the conditional expression type is double.

这篇关于三元运算符中不需要的 NullPointerException - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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