Set<Integer> set2 = map2.keySet();
for(Integer key :set2)
{
if(key>50 && key<150)
map2.remove(key);
}
System.out.println(map2);
运行后抛出ConcurrentModificationException。
换用迭代器,一样抛异常:
Set<Integer> set2 = map2.keySet();
Iterator<Integer> it = set2.iterator

在Java中,遍历Map集合时直接调用remove方法会导致ConcurrentModificationException异常。即使使用迭代器,也会遇到同样问题。解决办法是将要删除的键存储到另一个容器,然后遍历该容器并安全地从Map中移除对应键。

664

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



