I guess I might be missing something obvious here, but anyway lets see the code.
public static class FreeMap extends TreeMap<String, Integer> {
@Override
public Integer put(String key, Integer value) {
out.println(super.toString());
out.println(super.getClass().getName()+" "+key+" : "+value);
int i = super.put(key, value);//line 227
assert this.size() == 1;
return i;
}
}
public static void main(String[] args) {
FreeMap fm = new FreeMap();
fm.put("A", 10);
}
On Running this you will get a output as following:
{}
com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph$FreeMap A : 10
Exception in thread "main" java.lang.NullPointerException
at com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph$FreeMap.put(Graph.java:227)
at com.xxxxxxxxxxxxxxxxxxxxxxxx.Graph.main(Graph.java:212)
I can see super is referring to FreeMap, not TreeMap, if it would have thrown a StackOverflow Exception I could have understood. Why nullpointerexception?
Thanks in advance
Yes, because
putreturns the previous value:There is no previous value, so it’s returning
null, which you’re then unboxing, leading to an exception.Given that your method is already declared to return
Integer, the fix is easy. Change this:to this:
Or ideally, for readability:
Note that this would also be more efficient in the case that there was already a value for the key – there’s no benefit from unboxing and reboxing.