带条件运算符(三元运算符)但不带 if else 的空指针异常 [英] Nullpointer exception with conditional operator, (ternary operator) but not with if else

查看:75
本文介绍了带条件运算符(三元运算符)但不带 if else 的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用三元运算符,我会收到空​​指针异常.

I'm getting nullpointer exception if I use ternary operator.

Integer val = null;
Object res = val == null ? val : val.intValue();

但不是 if else

But not with if else

    Integer val = null;
    Object res;
  if( val == null ) {
      res  = val;
  } else {
      res = val.intValue();
  }

谁能解释一下为什么?

谢谢苏达尔

推荐答案

您遇到的行为源于确定三元条件表达式类型的规则.

The behavior you encountered results from the rules of determining the type of the ternary conditional expression.

在你的情况下,表达式的类型

In your case, the type of the expression

val == null ? val : val.intValue();

int.

这是由 JLS 指定的15.25.:

条件表达式的类型确定如下:

The type of a conditional expression is determined as follows:

  • 如果第二个和第三个操作数的类型相同(可能是 null 类型),那就是条件表达式的类型.

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.

如果第二个和第三个操作数之一是原始类型 T,另一个的类型是对 T 应用装箱转换(第 5.1.7 节)的结果,则条件表达式为T.

你的第二个操作数是Integer,你的第三个操作数是int,因此表达式的类型是int.

Your second operand is Integer and your third operand is int, therefore the type of the expression is int.

因此,当 val == null 时,val 被取消装箱(即为空值调用 val.intValue())和 NullPointerException 被抛出.

Therefore, when val == null, val is un-boxed (i.e. val.intValue() is called for a null value) and a NullPointerException is thrown.

在你的 if-else 表达式中,当 val 的值为 null 时,它不会被拆箱(因为你将它分配给了一个 Object 变量,所以没有 空指针异常.

In your if-else expression val is not un-boxed when its value is null (since you assign it to an Object variable, so there's no NullPointerException.

也就是说,由于您将一个 Integer 变量分配给一个 Object 变量,因此您在任一代码段中的条件都是毫无意义的(因为将 int 分配给了一个 Object 变量只需将 int 装回 Integer.

That said, since you are assigning an Integer variable to an Object variable, your conditions in either of the snippets are pointless (since assigning an int to an Object variable simply boxes the int back to Integer).

您可以简单地分配

Object res = val;

并获得相同的最终结果,无一例外.

and get the same end result without the exception.

这篇关于带条件运算符(三元运算符)但不带 if else 的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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