当我像这样编写我的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 Jablownull
映射,最好立即抛出异常。或者,如果有人向您的代码传递一个null
,则将您的映射设置为空映射。 - Eric Jablow