为什么返回null并分配给引用类型的三元条件表达式会导致NullPointerException? [英] Why does a ternary conditional expression returning null and assigned to a reference type cause a NullPointerException?

查看:122
本文介绍了为什么返回null并分配给引用类型的三元条件表达式会导致NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在java编程中使用三元条件表达式,但我遇到了一个问题:

I like to use the ternary conditional expression in java programming, but I experienced an issue :

以下代码是一个小例子,但是它显示了一个问题,我找到了。

The following code is a small example, but it shows the problem that I have found.

public class Example {

    public Example() {
        Double x = 0.0;    
        A a = new A();   
        x = a == null ? 0.0 : a.getY();   // Happens on this line    
        System.out.println(x);
    }

    class A {
        Double y = null;  
        private Double getY() {
            return y;
        }
    }

    public static void main(String[] args) {
        new Example();
    }

}

造成<$ c $的原因是什么c> NullPointerException ?

推荐答案

这是 JLS规则确定三元条件表达式的类型:

This results from the JLS rules of determining the type of the ternary conditional expression :


如果第二个和第三个操作数之一是原始类型T,另一个的类型是应用装箱转换的结果(第5.1节。 7)到T,然后条件表达式的类型是T.

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

这个规则意味着三元表达式的类型是 double 而不是 Double 。将 a.getY()方法返回的 Double 拆箱到 double 导致 NullPointerException ,因为该方法返回 null

This rule means that the type of the ternary expression is double and not Double. Unboxing the Double returned by your a.getY() method to double causes NullPointerException, since that method returns null.

a == null ? 0.0   : a.getY();
            double   Double      -> hence the type of the ternary expression is double

这篇关于为什么返回null并分配给引用类型的三元条件表达式会导致NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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