遍历List时直接调用list.remove()会抛ConcurrentModificationException,正确做法是仅通过Iterator或ListIterator自身的remove()方法删除元素。

在 Java 中,遍历 List 时直接调用 list.remove() 会触发 ConcurrentModificationException(并发修改异常),因为普通 for 循环或增强 for 循环底层依赖迭代器,而集合结构被外部修改后,迭代器的 modCount 和 expectedModCount 不一致,校验失败即抛异常。正确做法是**只通过迭代器自身的 remove() 方法删除当前元素**。
使用 Iterator 的 remove() 安全删除
这是最标准、最安全的方式。必须先调用 next() 获取元素,再调用 remove(),且每个 next() 后最多调用一次 remove():
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "b", "d"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("b".equals(s)) {
it.remove(); // ✅ 正确:由迭代器自己删除
}
}
// 结果:["a", "c", "d"]
使用 ListIterator 支持双向遍历与增删
若需从后往前删、或边遍历边添加元素,可用 ListIterator。它同样只允许调用其自身 remove() 或 add():
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
ListIterator<String> lit = list.listIterator(list.size());
while (lit.hasPrevious()) {
String s = lit.previous();
if ("c".equals(s)) {
lit.remove(); // ✅ 允许在 previous() 后调用
}
}
避免常见错误写法
- ❌ 增强 for 循环中调用
list.remove():for (String s : list) { if ("x".equals(s)) list.remove(s); }→ 必抛异常 - ❌ 普通 for 循环正向遍历时用
remove(i)且未调整索引:for (int i = 0; i < list.size(); i++) { if (cond) list.remove(i); }→ 会跳过下一个元素,且可能越界 - ❌ 迭代器 remove() 调用多次或未先调用 next():
it.remove(); it.remove();或it.remove();在next()前 → 抛IllegalStateException
替代方案:收集待删元素后批量移除
如果逻辑复杂、需多次判断,可先用另一个集合暂存要删的元素,遍历完再调用 removeAll()(注意:该操作本身线程不安全,仅适用于单线程场景):
立即学习“Java免费学习笔记(深入)”;
List<String> toRemove = new ArrayList<>();
for (String s : list) {
if (shouldRemove(s)) {
toRemove.add(s);
}
}
list.removeAll(toRemove); // ✅ 安全,但注意 removeAll 会遍历内部匹配,性能略低

















