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?