java中用iterator删除元素需严格遵循规则:必须先调next()再调remove(),且仅限一次;禁用集合自身remove()方法,否则抛concurrentmodificationexception;推荐java 8+的removeif()简化操作。

Java 中用 Iterator 删除元素时,只要严格遵守调用顺序和规则,就不会抛 ConcurrentModificationException。核心是:必须用迭代器自己的 remove() 方法,且只能在 next() 之后立即调用一次。
必须先 next(),再 remove()
Iterator 的 remove() 不是“随时可删”,它依赖上一次 next() 定位到的当前元素。没调 next() 就调 remove(),会直接抛 IllegalStateException;next() 后连续调两次 remove(),也会抛这个异常。
- ✅ 正确:
it.next(); it.remove(); - ❌ 错误:
it.remove();(没 next) - ❌ 错误:
it.next(); it.remove(); it.remove();(重复 remove)
不能混用集合自身的 remove() 方法
哪怕只调一次 list.remove(…) 或 map.remove(…),也会让迭代器内部的 expectedModCount 和集合的 modCount 失配,下一次 hasNext() 或 next() 就触发 ConcurrentModificationException。
- 遍历中所有删除动作,必须统一走
it.remove() - for-each 循环里写
list.remove()是典型错误,它本质还是用了迭代器,但你无法控制 remove 行为
不同集合的写法要点
Iterator 接口通用,但获取方式略有差异:
-
List:直接
list.iterator() -
Set:直接
set.iterator() -
Map:必须转成视图,如
map.entrySet().iterator()或map.keySet().iterator();不能对 map 本身调 iterator
例如删 Map 中 value 小于 10 的项:
Iterator<map.entry integer>> it = map.entrySet().iterator();<br>
while (it.hasNext()) {<br>
Map.Entry<string integer> e = it.next();<br>
if (e.getValue()
<h3>替代方案:removeIf 更简洁(Java 8+)</h3>
<p>如果只是按条件批量过滤,<code>removeIf()</code> 是更推荐的选择。它底层仍用 Iterator.remove(),但封装了逻辑,一行搞定,不易出错。</p>
<ul>
<li><code>list.removeIf(s -> s == null || s.trim().isEmpty());</code></li>
<li><code>map.entrySet().removeIf(e -> e.getKey().startsWith("tmp")); </code></li>
<li>注意:它不适用于需要在删除前做复杂处理(比如记录被删元素、跨集合查表)的场景</li>
</ul></string></map.entry>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











