gpt4 book ai didi

java - 使用 Java 三元运算符时的奇怪行为

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:47 30 4
gpt4 key购买 nike

当我这样写 java 代码时:

Map<String, Long> map = new HashMap<>()
Long number =null;
if(map == null)
number = (long) 0;
else
number = map.get("non-existent key");

应用程序按预期运行,但是当我这样做时:

Map<String, Long> map = new HashMap<>();
Long number= (map == null) ? (long)0 : map.get("non-existent key");

我在第二行得到一个 NullPointerException。调试指针从第二行跳转到java.lang.Thread类中的这个方法:

 /**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}

这里发生了什么?这两个代码路径完全等同,不是吗?


编辑

我正在使用 Java 1.7 U25

最佳答案

它们不等价。

这个表达式的类型

(map == null) ? (long)0 : map.get("non-existent key");

long,因为真实结果的类型是long

此表达式为 long 类型的原因来自 §15.25 of the JLS 部分:

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.

当您查找不存在的键时,map 返回 null。因此,Java 试图将其拆箱为 long。但它是 null。所以它不能,你会得到一个 NullPointerException。您可以通过以下方式解决此问题:

Long number = (map == null) ? (Long)0L : map.get("non-existent key");

然后你就没事了。

然而,在这里,

if(map == null)
number = (long) 0;
else
number = map.get("non-existent key");

因为 number 被声明为 Long,所以拆箱到 long 永远不会发生。

关于java - 使用 Java 三元运算符时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17549666/

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