先来看看《阿里巴巴Java开发手册》中的一段
【强制】不要在 foreach 循环里进行元素的 remove/add 操作。remove 元素请使用 Iterator
方式,如果并发操作,需要对 Iterator 对象加锁。
反例:
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
for (String temp : a) {
if("1".equals(temp)){
a.remove(temp);
}
}
说明:这个例子的执行结果会出乎大家的意料,那么试一下把“1”换成“2”,会是同样的结
果吗?
正例:
Iterator<String> it = a.iterator();
while(it.hasNext()){
String temp = it.next();
if(删除元素的条件){
it.remove();
}
}
当1的时候,能够正确输出remove 以后的ArrayList 当2的时候,抛出了 ConcurrentModificationException
看一段ArrayList 的forEachRemaining 方法的源码
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
本质上是隐式的 iterator 由于没有重新设置 expectedModCount ,当你使用 list.remove() 后遍历执行 iterator.next() 时就会报ConcurrentModificationException