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

查看:88
本文介绍了三元运算符中不需要的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;

在这种情况下,编译器会看到 Double double 作为三元条件运算符的第二个和第三个参数,并确定表达式的类型应为 double 。因此,它将 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.

如果第二和第三操作数小于code> null 和 double ,条件表达式类型是 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.

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

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

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

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