三元表达式中的 NullPointerException 与 null Long [英] NullPointerException in ternary expression with null Long

查看:15
本文介绍了三元表达式中的 NullPointerException 与 null Long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面这行代码会产生一个NullPointerException?

Why does the following line of code produce a NullPointerException?

Long v = 1 == 2 ? Long.MAX_VALUE : (Long) null;

我知道正在对 null 执行拆箱,但为什么呢?

I understand that unboxing is being performed on null, but why?

注意

Long v = (Long) null;

不产生异常.

推荐答案

所以看起来很明显只有当条件为真时才需要装箱,如果条件为假则不应该进行装箱.但是,三元运算符表达式必须具有特定的静态 类型.所以我们有Longlong.JLS 声明结果将是原语(同样 - 想象一下,如果运算符是,例如,+ 甚至 ==).所以三元运算符会强制拆箱,只有这样赋值才会导致装箱.

So it looks obvious that you only have to box if the condition is true, and there should be no boxing if the condition is false. However the ternary operator expression must have a particular static type. So we have Long and long. The JLS states that the result will be the primitive (just as well - imagine if the operator was, say, + or even ==). So the ternary operator will force the unboxing, and only then does the assignment cause a boxing.

如果你用等效的 if-else 替换代码,那么你只需要一个从 longLong 的赋值和从 LongLong,它不会有任何拆箱,所以运行良好.

If you were to replace the code with the equivalent if-else, then you'd just have an assignment from long to Long and from Long to Long, which wouldn't have any unboxing and so run fine.

IIRC,这涵盖的是 Bloch &Gafter 的 Java 拼图.

IIRC, this is covered is Bloch & Gafter's Java Puzzlers.

这篇关于三元表达式中的 NullPointerException 与 null Long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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