TreeMap中的空指针异常

时间:2012-08-30 09:33:05

标签: java nullpointerexception treemap

我试图实现一个简单的树形图来计算整数的出现次数,但它给了我NullPointerException并且我不知道如何修复它。

Exception in thread "main" java.lang.NullPointerException
    at exercises.CountOccurances_20_07.main(CountOccurances_20_07.java:21)

以下是代码:

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());
    }
}

4 个答案:

答案 0 :(得分:7)

在你的情况下,map.get(key)返回null并且永远不会为0.你也在使用密钥,查找听起来不对的自己。

for(int key: list) {
    Integer count = map.get(key);
    if (count == null) count = 0;
    map.put(key, count+1);
}

答案 1 :(得分:2)

第21行的NullPointerException

int value = map.get(key).intValue(); // line 21

是因为如果地图中不存在map.get(key)key将返回null。

你应该使用

if(!map.containsKey(key)){
}

而不是

if(map.get(key) == 0) {
}

评估为

if(null == 0){
}

并且您的条件为假,然后控件转到第21行。

答案 2 :(得分:1)

更改

map.get(key) == 0 

map.get(key) == null  

!map.contains(key)

答案 3 :(得分:1)

您的代码存在许多明显的缺陷。

Map是作为空地图构建的,但会立即查询并且get结果已取消装箱:

Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
...
if(map.get(key) == 0)
对于不存在的映射条目,

get返回null,而不是零,并且对于空参数,取消装箱将失败。


此处list已初始化,但随后会检查其长度:

int[] list = {2, 3, 40, 3, 5, 4, 3, 3, 3, 2, 0};
if(list.length > 1)

这是一项冗余检查,请将其删除。


for(int i: list)
{
  int key = list[i];

使用int i的方式很可能是错误的。为循环增强的将每个数组元素依次分配给i,因此您应该只有for (int key : list)。{/ p>


int value = map.get(key).intValue(); // line 21

调用intValue是多余的 - 自动取消装箱会解决这个问题。在尝试取消装箱之前,您需要确保该值不为空。