Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when adding to HashMap

Tags:

java

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?

like image 966
zr870 Avatar asked Mar 26 '14 04:03

zr870


2 Answers

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.

like image 128
locoyou Avatar answered Oct 16 '22 02:10

locoyou


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.

like image 31
Sagar Gandhi Avatar answered Oct 16 '22 02:10

Sagar Gandhi