When I write my java code like this:
Map<String, Long> map = new HashMap<>()
Long number =null;
if(map == null)
number = (long) 0;
else
number = map.get("non-existent key");
the app runs as expected but when I do this:
Map<String, Long> map = new HashMap<>();
Long number= (map == null) ? (long)0 : map.get("non-existent key");
I get a NullPointerException on the second line. The debug pointer jumps from the second line to this method in the java.lang.Thread class:
/**
* 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);
}
What is happening here? Both these code paths are exactly equivalent isn't it?
Edit
I am using Java 1.7 U25
map
yourself; if it isnull
, your runtime system is broken. Since this is obviously a shortened version of other work you are doing, I would suggest you ensure that objects are always initializedso you don't have to do themap == null
checks. The keys are your problem. – Eric Jablow Jul 9 at 13:57null
map to your code. Or, if someone passes in anull
to your code, set your map to an empty one instead. – Eric Jablow Jul 9 at 18:19