map.forch执行remove方法报错
前序
最近在写项目的时候,使用了map.Forech
循环遍历去执行remove
方法结果发现抛出ConcurrentModificationException
问题。以下是模拟代码展示
public class StringDemo1 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
map.forEach((key, value) -> {
if(key.equals("2")) {
map.remove(key);
}
});
System.out.println(map.size());
}
}
原因
使用了 HashMap.forEach
来遍历 map
,在遍历过程中尝试使用 map.remove(key)
删除元素 "2"
。
这是不被允许的,因为:
forEach
底层是基于 迭代器(Iterator) 实现的;- 在使用迭代器遍历集合时,不能直接对集合进行结构性的修改(比如添加或删除元素),否则就会抛出
java.util.ConcurrentModificationException
正确的做法
- 使用
Iterator
进行显式遍历,并通过iterator.remove()
方法删除:
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getKey().equals("2")) {
iterator.remove(); // 安全删除
}
}
System.out.println(map.size()); // 输出 3
- 或者改用CurrentHashMap代替HashMap
public class StringDemo1 {
public static void main(String[] args) {
Map<String, String> map = new CurrentHashMap<>();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
map.forEach((key, value) -> {
if(key.equals("2")) {
map.remove(key);
}
});
System.out.println(map.size());
}
}