【发布时间】:2013-08-09 13:43:50
【问题描述】:
这是生成 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。我的猜测是在我的 myMap.put() 方法中使用 new HashSet<Long>() 导致它。但我不完全确定。
【问题讨论】:
-
事实上,此代码不会产生 NPE。还有一些事情你没有告诉我们。
-
@Qwerky 代码太多了,我不确定要包括什么:-/
-
我在下面的回答可能就是这里实际发生的情况。但是......这只是一个有根据的猜测,因为正如@Qwerky 所说,没有足够的信息。
-
我运行了代码,它对我来说确实很好。您还可以发布您的 methodReturnRandomLong() 和 methodreturnRandomInt()
-
当您在上面提供的代码示例中调用
hashset.add时,您将引用您创建的唯一hashset实例。
标签: java map nullpointerexception set