在 foreach 中调用 list.remove() 会因 modcount 与 expectedmodcount 不一致触发 concurrentmodificationexception;而 iterator.remove() 会同步更新两者,确保安全。

因为在 foreach 循环中调用 list.remove() 会绕过迭代器的结构变更控制机制,导致集合的修改计数(modCount)和迭代器预期值(expectedModCount)不一致,触发 fail-fast 检查而抛出 ConcurrentModificationException。
foreach 实质是迭代器遍历
Java 编译器会把:
for (String s : list) { if (s == null) list.remove(s); }
自动转为:
Iterator<string> it = list.iterator();<br>while (it.hasNext()) {<br> String s = it.next(); // 这里会检查 modCount == expectedModCount<br> if (s == null) list.remove(s); // 直接改 list,modCount++,但 it 不知情<br>}</string>
也就是说,遍历动作由迭代器负责,但删除动作却由 List 自己执行——两者状态脱节。
ArrayList 的 fail-fast 设计机制
ArrayList 内部维护一个 modCount 字段,记录结构性修改次数(如 add、remove、clear)。每个迭代器实例在创建时会复制该值到 expectedModCount。每次调用 next() 或 forEachRemaining() 前,都会执行 checkForComodification():
- 若
modCount != expectedModCount,立即抛出ConcurrentModificationException -
list.remove()会令modCount++,但迭代器未同步更新expectedModCount - 下一次
it.next()就会失败
为什么 iterator.remove() 是安全的
迭代器自己的 remove() 方法在删除后主动同步了状态:
- 它先校验
lastRet >= 0(确保刚调用过next()) - 调用
ArrayList.this.remove(lastRet)完成实际删除 - 紧接着更新
cursor和lastRet,并重置expectedModCount = modCount
这样就维持了迭代器与底层数组的一致性,不会触发异常。
常见误区与验证线索
有人发现“删第一个元素不报错,删第二个就崩”,这其实取决于循环执行时机:
- 第一次
next()成功,进入 if 判断,执行list.remove()→modCount变了 - 第二次
next()前检查失败 → 异常抛出 - 但如果列表只剩一个元素,删完后
hasNext()返回 false,循环自然结束,就不会走到下一次next()检查
这不是“有时安全”,而是异常触发时机刚好被跳过——行为不可靠,绝不能依赖。











