异常:ConcurrentModificationException
现象:在遍历Map过程中,使用map.remove(key)来修改和删除元素, 引发此异常
代码:
HashMap<String, String> map = new HashMap<String, String>();
map.put("one", "apple");
map.put("two", "microsoft");
map.put("three", "ibm");
for (String key : map.keySet()) {
if ("two".equalsIgnoreCase(key)) {
map.remove(key);
}
}

本文介绍在使用Java HashMap遍历过程中尝试删除元素时遇到的ConcurrentModificationException异常。通过具体示例代码展示了错误的发生,并提供了避免该异常的方法。了解这一常见问题有助于开发者在处理集合类时避免潜在陷阱。

1万+

被折叠的 条评论
为什么被折叠?



