Saurabh Tripathi
Saurabh Tripathi

Reputation: 105

The Subclass of java.util.TreeMap gives NullPointerException on call put(key, value) method

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

Upvotes: 5

Views: 339

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503859

Yes, because put returns the previous value:

Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

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:

int i = super.put(key, value);

to this:

Integer i = super.put(key, value);

Or ideally, for readability:

Integer oldValue = super.put(key, value);

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.

Upvotes: 11

Related Questions