难以跟踪NullPointerException

时间:2013-08-09 13:43:51

标签: java map nullpointerexception set

以下是生成NPE的代码段,如果不足以让您了解可能出现的问题,请告诉我。

我有一个以这种方式实例化的地图:

Map<Integer, Set<Long>> myMap = new HashMap<Integer, Set<Long>>();

我正在努力做到以下几点:

long randomLong = methodReturnsRandomLong();
int randomInt = methodReturnsRandomInt();

if(myMap.isEmpty()) { // the map is empty at this point
   myMap.put(randomInt, new HashSet<Long>());
   myMap.get(randomInt).add(randomLong);
}

// Now I want to remove it
myMap.get(randomInt).remove(randomLong);  // Here is what generates the NPE

我不明白可能导致NPE的原因。我的猜测是在new HashSet<Long>()方法中使用myMap.put()导致它。但我不完全确定。

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为地图可能不是空的,但会有randomInt值的条目。

您正在寻找的是:

//does a mapping exist for this specific value?
if(!myMap.containsKey(randomInt)){
    myMap.put(randomInt, new Hashset<Long>());
    myMap.get(randomInt).add(randomLong);
}
//now this value will be defined here.
myMap.get(randomInt).remove(randomLong);

调用map.isEmpty只是检查没有映射是否存在。您真的想知道randomInt值是否存在映射,而不是存在任何映射。

我知道你说地图在这一点上是空的,但我之前已经看过几次这个错误了。这通常是与此类似情况的原因。