Iterator.remove()是唯一安全的边遍历边删除方式,因其同步更新modCount与expectedModCount避免fail-fast;需严格遵循“获取迭代器→hasNext/next遍历→满足条件即remove”三步,且每次remove必须紧跟一次next。

不能直接用 list.remove() 在增强 for 循环或普通 for 遍历时删元素,否则会抛 ConcurrentModificationException。正确做法是使用 Iterator.remove() —— 它是唯一安全、标准的“边遍历边删除”方式。
为什么 Iterator.remove 是安全的
Iterator 的 remove() 方法被设计为与当前迭代状态同步:它只在刚调用过 next() 后才允许执行,且会主动更新内部的 modCount 和 expectedModCount,避免触发快速失败(fail-fast)机制。普通 list.remove() 会修改结构但不通知迭代器,导致校验失败。
正确使用步骤(三步缺一不可)
- 获取集合的迭代器:
Iterator<String> it = list.iterator();</li> <li>用 <code>it.hasNext()
+it.next()遍历,**不要**在循环体里调用list.remove() - 在满足删除条件时,立刻调用
it.remove()(必须紧跟在it.next()之后,且每调一次next()最多调一次remove())
典型代码示例
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie", "Bob", "David"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
if ("Bob".equals(name)) {
it.remove(); // ✅ 安全删除
}
}
// 结果:["Alice", "Charlie", "David"]
常见误区提醒
- ❌ 在同一个
next()后多次调用it.remove()→ 抛IllegalStateException - ❌ 在还没调用
next()就调it.remove()→ 同样抛IllegalStateException - ❌ 混用
it.remove()和list.remove()→ 可能仍触发ConcurrentModificationException - ⚠️
remove()删除的是上一次next()返回的元素,不是当前判断的“逻辑上一个”——注意索引语义
不复杂但容易忽略:只要严格遵循“next → 判断 → remove(可选)”这个节奏,就能零异常地完成遍历中剔除。

















