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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With