iterator.remove()是遍历list时安全删除元素的标准方法,必须通过迭代器自身remove()删除,不可调用集合remove()或多次调用remove(),否则抛illegalstateexception或concurrentmodificationexception。

用 Iterator.remove() 在遍历 List 时安全删除元素,是避免 ConcurrentModificationException 的标准做法。核心在于:**必须通过迭代器自身的 remove() 方法删除,不能调用集合的 remove() 方法,也不能在调用 next() 前多次调用 remove()。**
为什么不能直接用 for-each 或普通 for 循环删?
for-each 循环底层使用的是迭代器,但隐藏了控制权;若在循环中直接调用 list.remove(),会触发快速失败机制(fail-fast),抛出 ConcurrentModificationException。普通 for 循环从后往前删虽可行,但逻辑易错、可读性差,且无法动态判断“无效数据”的复杂条件。
正确使用 Iterator.remove() 的三步法
只需三步,清晰可控:
- 获取列表的迭代器:
Iterator<t> it = list.iterator();</t>
- 用
while(it.hasNext()) 遍历,每次调用 <code>it.next()获取当前元素 - 在满足删除条件时,立刻调用
it.remove()—— 注意:该方法只能在上一次next()调用之后执行一次
典型示例:剔除 null 或空字符串
假设有一个 List<string></string>,需移除所有 null 和长度为 0 的字符串:
List<string> list = new ArrayList(Arrays.asList("hello", "", null, "world", " "));
Iterator<string> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s == null || s.trim().isEmpty()) {
it.remove(); // 安全删除
}
}
// 结果:["hello", "world"]
</string></string>
常见陷阱与提醒
-
remove() 只能调用一次:连续写两次
it.remove()会抛IllegalStateException
-
不能和 List.remove() 混用:哪怕只调用一次
list.remove(),也会破坏迭代器状态 -
不适用于并发修改场景:多线程下仍需额外同步(如用
CopyOnWriteArrayList) -
forEach + remove 不行:Lambda 中的
list.remove()同样触发异常,不是语法糖能绕过的











