Reputation: 405
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());
}
}
Upvotes: 2
Views: 10927
Reputation: 200296
There are many obvious deficiencies with your code.
Map
is constructed in place as an empty map, but is immediately queried and the get
result unboxed:
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
...
if(map.get(key) == 0)
get
returns null
for a non-existent map entry, not a zero, and unboxing will fail for a null argument.
Here list
is initialized in place, but is then checked for length:
int[] list = {2, 3, 40, 3, 5, 4, 3, 3, 3, 2, 0};
if(list.length > 1)
This is a redundant check, remove it.
for(int i: list)
{
int key = list[i];
The way you use int i
is very probably wrong. The enhanced for loop assigns each array element in turn to i
, so what you should in all probability have is just for (int key : list)
.
int value = map.get(key).intValue(); // line 21
Calling intValue
is redundant -- auto-unboxing will take care of this. You do need to make sure that the value is not null before trying to unbox.
Upvotes: 1
Reputation: 14373
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.
Upvotes: 2
Reputation: 533880
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);
}
Upvotes: 7
Reputation: 29731
change
map.get(key) == 0
to
map.get(key) == null
or
!map.contains(key)
Upvotes: 1