13

I am getting a NullPointerException when adding data to a HashMap. I am writing a class to count the given frequencies of certain Objects. Here is my code (stripped of any unnecessary details):

public class FrequencyCounter {

    private Map<Object, Integer> freq;

    public FrequencyCounter() {
        freq = new HashMap<Object, Integer>();
    }

    public int add(Object key) {        
        System.out.println("Map is null: " + (freq == null));
        System.out.println("Key is null: " + (key == null));
        if (freq.containsKey(key)) {
            return freq.put(key, freq.get(key) + 1);
        }
        return freq.put(key, 1);
    }

    public static void main(String[] args) {
        FrequencyCounter fc = new FrequencyCounter();
        fc.add(new Object());
    }
}

The NPE is occuring on the line return freq.put(key, 1); Both println statements print false.

Do any of you know what I may be doing wrong?

1

3 Answers 3

17

This is because HashMap.put(key, value) will return the previous value associated with key, or null. In your code, you cannot return freq.put(key,1) as int because it is null.

Sign up to request clarification or add additional context in comments.

5 Comments

I added a print statement to check if freq.put(key, 1) was returning null and it was. Thank you.
I'm wonder, why there is no compile time error, in docs.oracle.com/javase/tutorial/java/data/autoboxing.html such condition is not provided
@atomAltera I think this can help you stackoverflow.com/questions/11897883/…
@atomAltera The compiler cannot know It is null because freq.put(key, 1) will return a Integer object.
@locoyou Yes, but this Integer object (more precisely - pointer to Integer object) could point to nothing. But I think java developers doing this right, I mean implicit unboxing
2

add method returns int. int is primitive data type , which can not be null. freq.put(key,1)returns null so it throws exception. change return type of add method to Integer or add null check.

1 Comment

That's what I did, thanks. I just returned 0 because prior to this, the given object was present in the Map 0 times.
1

since put() may return null so you must change return type to Integer which can be null:

public Integer add(Object key) {        
    System.out.println("Map is null: " + (freq == null));
    System.out.println("Key is null: " + (key == null));
    if (freq.containsKey(key)) {
        return freq.put(key, freq.get(key) + 1);
    }
    return freq.put(key, 1);
}

and must validate return value for null before using it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.