【问题标题】:Difficulty tracking a NullPointerException难以跟踪 NullPointerException
【发布时间】: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&lt;Long&gt;() 导致它。但我不完全确定。

【问题讨论】:

  • 事实上,此代码不会产生 NPE。还有一些事情你没有告诉我们。
  • @Qwerky 代码太多了,我不确定要包括什么:-/
  • 我在下面的回答可能就是这里实际发生的情况。但是......这只是一个有根据的猜测,因为正如@Qwerky 所说,没有足够的信息。
  • 我运行了代码,它对我来说确实很好。您还可以发布您的 methodReturnRandomLong() 和 methodreturnRandomInt()
  • 当您在上面提供的代码示例中调用hashset.add 时,您将引用您创建的唯一hashset 实例。

标签: java map nullpointerexception set


【解决方案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 只是检查no 映射是否存在。您确实想知道randomInt 值是否存在映射,而不是是否存在任何映射。

我知道您说此时地图为空,但我之前已经多次看到此错误。这通常是类似情况的原因。

【讨论】:

  • 这是我的问题!谢谢(天哪,我觉得自己像个菜鸟):(
  • 很高兴听到这个消息!每个人都必须在某个时候学习。请记住接受此答案以结束此问题。
猜你喜欢
  • 2012-09-26
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 2013-06-27
  • 2012-05-06
  • 2019-10-02
  • 2012-05-31
  • 1970-01-01
相关资源
最近更新 更多