【发布时间】:2013-07-09 13:38:13
【问题描述】:
当我这样写我的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,则您的运行时系统已损坏。由于这显然是您正在做的其他工作的缩短版本,我建议您确保始终初始化对象,这样您就不必进行map == null检查。关键是你的问题。 -
@Eric Jablow 这只是我的代码的简化版本。有问题的地图实际上是从另一个按需动态创建的地方检索的。这就是为什么要检查。在这里我包括了初始化,以便回答我的问题时没有执行 if-true 案例的人清楚
-
我现在明白了。如果有人将
null映射传递给您的代码,最好的办法可能是立即抛出异常。或者,如果有人将null传递给您的代码,请将您的地图设置为空地图。
标签: java nullpointerexception ternary-operator