gpt4 book ai didi

java - 双三元Integer初始化导致空指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:41 25 4
gpt4 key购买 nike

为什么将 x 设置为 null 就没问题:

boolean condition1 = false;
Integer x = condition1 ? 1 : null;

将 x 设置为 2 就可以了:

boolean condition1 = false, condition2 = true;
Integer x = condition1 ? 1 : condition2? 2 : null;

但是,x 应该设置为 null 会导致 java.lang.NullPointerException

boolean condition1 = false, condition2 = false;
Integer x = condition1 ? 1 : condition2 ? 2 : null;

一个解决方案是使用:

Integer x = condition1 ? (Integer)1 : condition2 ? 2 : null;

但我不太清楚为什么单个三元运算符可以正常工作,但双元运算符却不行。

最佳答案

(我仍然认为这是一个 duplicate 在你做了一些拆包之后,但是嘿......)

将一个语句展开为两个:

// Not exactly the same, but close...
Integer tmp = condition2 ? 2 : null;
Integer x = condition1 ? 1 : (int) tmp;

这不完全相同,因为它评估 condition2 ? 2 : null 即使 condition1 为 false - 您可以改为使用方法调用对其进行建模,但在您担心的情况下,condition1条件 2 为假。

现在,您可能会问为什么我们要在此处强制转换为 int。那是因为 JLS 15.25.2 :

The type of a numeric conditional expression is determined as follows:

  • ...
  • 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.
  • ...

我们有 intInteger,所以这匹配 T = int... 和“内部”条件表达式的结果必要时拆箱...这就是导致问题的原因。

1 转换为 Integer 会改变这一点,因此外部表达式的类型也是 Integer (因为第二个和第三个操作数然后输入 Integer) 所以没有拆箱。

请注意,在我们的扩展中,tmp 是一个 Integer,它确实是“内部”条件表达式的类型,因为第三个操作数的类型是空类型,而不是 Integer。你也可以只用一个条件让它失败:

Integer bang = false ? 2 : (Integer) null;

基本上,具有 intInteger 类型的第二个和第三个操作数的条件运算符将执行第三个操作数的拆箱(结果为 int 类型),但是第二个和第三个操作数分别为 intnull 类型的条件运算符将拆箱,结果类型是整数

关于java - 双三元Integer初始化导致空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com