Iterator的remove()只能在next()后立即调用一次,用于删除上一次next()返回的元素;其他任何集合修改操作都会导致ConcurrentModificationException。

Java Iterator 的 remove() 方法只能在调用 next() 之后立即调用一次,且不能在遍历开始前、或连续调用两次,否则会抛出 IllegalStateException。
必须先调用 next() 才能 remove
remove() 不是“删除当前元素”,而是“删除上一次 next() 返回的元素”。也就是说,它依赖于迭代器内部的状态(即最近一次返回的元素)。
- 创建迭代器后直接调用
remove()→ 抛出异常 - 调用一次
next()后,再调用remove()→ 合法,删除刚取到的那个元素 - 连续调用两次
remove()(中间没调next())→ 抛出异常
不能用 for-each 循环配合 remove
增强 for 循环(for (E e : list))底层使用了迭代器,但隐藏了对 next() 和 remove() 的控制。在其中直接调用集合的 remove() 方法(如 list.remove(e)),会导致 ConcurrentModificationException。
正确做法是显式获取迭代器:
在调试 Java 后端 API 故障时使用此技能,尤其适用于以下任务:分析日志、跨 Controller、Service 和 Mapper 层追踪请求、定位异常根因、检查 SQL 执行或参数流转,以及生成简洁的诊断结论与修复方案。
立即学习“Java免费学习笔记(深入)”;
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("target".equals(s)) {
it.remove(); // ✅ 安全删除
}
}
remove() 是唯一安全的遍历中删除方式
在使用迭代器遍历时,除了 it.remove(),其他任何修改集合结构的操作(如 list.add()、list.clear()、list.remove(0) 等)都会导致迭代器失效,后续调用 next() 或 remove() 抛出 ConcurrentModificationException。
- ✅ 允许:仅调用
it.remove()(且满足调用时机) - ❌ 禁止:调用集合自身的增删改方法
- ⚠️ 注意:某些并发集合(如
CopyOnWriteArrayList)的迭代器支持弱一致性,remove()可能不生效或行为不同,需查文档
常见误用与修复示例
错误写法:
Iterator<Integer> it = list.iterator();
it.remove(); // IllegalStateException:还没 next()
while (it.hasNext()) {
it.next();
it.remove(); // ❌ 每次都删,但没判断条件;若 next() 后没做处理就删,逻辑易错
}
推荐写法:
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer val = it.next();
if (val % 2 == 0) { // 满足条件才删
it.remove(); // ✅ 位置正确,一次 next 对应至多一次 remove
}
}

















