我有一段简单的代码,它循环遍历一个映射,检查每个条目的条件,并在该条件为真时对条目执行一个方法。之后,该条目将从 map 中删除。
为了从 map 中删除条目,我使用了 Iterator
来避免 ConcurrentModificationException
。
除了我的代码确实在 it.remove()
行抛出异常:
Caused by: java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(Unknown Source) ~[?:1.8.0_161]
at package.Class.method(Class.java:34) ~[Class.class:?]
经过长时间的搜索,我找不到解决此问题的方法,所有答案都建议使用 Iterator.remove()
方法,但我已经在使用它了。 Map.entrySet()
的文档明确指出可以使用 Iterator.remove()
方法从集合中删除元素。
如有任何帮助,我们将不胜感激。
我的代码:
Iterator<Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<K, V> en = it.next();
if (en.getValue().shouldRun()) {
EventQueue.invokeLater(()->updateSomeGui(en.getKey())); //the map is in no way modified in this method
en.getValue().run();
it.remove(); //line 34
}
}
最佳答案
如果您无法将 HashMap
更改为 ConcurrentHashMap
,您可以对您的代码使用另一种方法。
您可以创建一个包含要删除的条目的条目列表,然后遍历它们并将它们从原始 map 中删除。
例如
HashMap<String, String> map = new HashMap<>();
map.put("1", "a1");
map.put("2", "a2");
map.put("3", "a3");
map.put("4", "a4");
map.put("5", "a5");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
List<Map.Entry<String, String>> entries = new ArrayList<>();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
if (next.getKey().equals("2")) {
/* instead of remove
iterator.remove();
*/
entries.add(next);
}
}
for (Map.Entry<String, String> entry: entries) {
map.remove(entry.getKey());
}
关于java - 使用迭代器删除条目时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171751/