I have tried to implement a simple treemap to count the occurances of integers, but it is giving me a NullPointerException and I don't know how to fix it.
Exception in thread "main" java.lang.NullPointerException
at exercises.CountOccurances_20_07.main(CountOccurances_20_07.java:21)
Here is the code:
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class CountOccurances_20_07
{
public static void main(String[] args)
{
int[] list = {2, 3, 40, 3, 5, 4, 3, 3, 3, 2, 0};
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for(int i: list)
{
int key = list[i];
if(list.length > 1)
{
if(map.get(key) == 0)
{
map.put(key, 1);
}
else
{
int value = map.get(key).intValue(); // line 21
value ++;
map.put(key, value);
}
}
}
//get all entries into set
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
//get key and value from entry set
for(Map.Entry<Integer, Integer> entry: entrySet)
System.out.println(entry.getValue() + "\t" + entry.getKey());
}
}
In your case map.get(key) is returning null and will never be 0. Also you are using the key, to lookup up itself which doesn't sound right.
for(int key: list) {
Integer count = map.get(key);
if (count == null) count = 0;
map.put(key, count+1);
}
The NullPointerException at line 21
int value = map.get(key).intValue(); // line 21
is due to the fact that map.get(key) would return null if the key is not present in the map.
You should use
if(!map.containsKey(key)){
}
instead of
if(map.get(key) == 0) {
}
as it evaluates to
if(null == 0){
}
and your condition is false and then the control goes to line 21.
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