Eventually I got the answer, but it puzzled me for a while.
Why does the following code throws NullPointerException when run?
import java.util.*;
class WhyNullPointerException {
public static void main( String [] args ){
// Create a map
Map<String,Integer> m = new HashMap<String,Integer>();
// Get the previous value, obviously null.
Integer a = m.get( "oscar" );
// If a is null put 1, else increase a
int p = a == null ?
m.put( "oscar", 1) :
m.put( "oscar", a++ ); // Stacktrace reports Npe in this line
}
}
You are assigning
int p
to the return value ofm.put()
. Butput()
returnsnull
in this situation, and you can't assign anint
tonull
.From the Javadocs for
HashMap.put()
:Because
m.put
returnsnull
(which indicates that there's no "previous" value) while you're trying to assign it toint
. Replaceint p
byInteger p
and it will work.This is specified in JLS 5.1.8:
Unrelated to the problem, just a side suggestion with DRY in mind, consider writing it so:
It's a bit more readable :)