【发布时间】:2021-10-14 21:12:46
【问题描述】:
这是我在解决leetcode问题954. Array of Doubled Pairs时遇到的。
这是一个存储每个值的计数的全局映射。我使用下面的这个函数来检查列表中的值(也在地图中)是否全部配对(如果地图有value和value * 2)。
Map<Integer, Integer> map;
private boolean isPaired( List<Integer> list) {
for(int key : list) {
if (map.containsKey(key)) {
if (map.containsKey(key * 2)) {
updateMap(key);
updateMap(key * 2);
} else {
return false;
}
}
}
return true;
}
private void updateMap(int key) {
int value = map.get(key);
if (value - 1 == 0) {
map.remove(key);
} else {
map.put(key , value - 1);
}
}
对于这种情况(9945 0s、10052 1s 和 10003 2s),它会抛出 NullPointerException。这是异常消息:
java.lang.NullPointerException
at line 54, Solution.updateMap
at line 44, Solution.isPaired
at line 26, Solution.canReorderDoubled
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
当我将函数 isPaired 更改为以下代码时:
private boolean isPaired(List<Integer> list) {
for(int key : list) {
if (map.containsKey(key)) {
updateMap(key);
if (map.containsKey(key * 2)) {
updateMap(key * 2);
} else {
return false;
}
}
}
return true;
}
NullPointerException 不再发生。 为什么会这样?
【问题讨论】:
-
也许您想发布minimal reproducible example 以及您遇到的错误的完整详细信息。
-
感谢您的建议khelwood。
标签: java nullpointerexception hashmap