iterator.remove()是唯一安全的遍历中删除方式,因其同步更新modcount与expectedmodcount;必须先next()再remove(),且不可连续调用或未next就remove。

不能直接用 list.remove() 在 for-each 或普通 for 循环中删除元素,否则会抛 ConcurrentModificationException。正确方式是使用 Iterator.remove() —— 它是唯一安全的、在遍历过程中删除当前元素的方法。
为什么 Iterator.remove 是安全的
Iterator 的 remove() 方法被设计为与迭代过程协同工作:它会同步更新内部的 modCount 和 expectedModCount,避免触发快速失败(fail-fast)机制。而 list.remove() 会修改集合结构但不通知迭代器,导致校验失败。
标准写法:先 next(),再 remove()
必须严格遵循“先调用 next() 获取元素 → 再调用 remove()”的顺序。不能跳过 next() 直接删,也不能对同一个元素重复调用 remove()(会抛 IllegalStateException)。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- ✅ 正确:
it.next(); it.remove(); - ❌ 错误:
it.remove();(没调用 next) - ❌ 错误:
it.next(); it.remove(); it.remove();(重复删)
典型应用场景示例
比如剔除所有 null 元素或满足某条件的字符串:
List<string> list = new ArrayList(Arrays.asList("a", null, "b", "", "c"));
Iterator<string> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s == null || s.isEmpty()) {
it.remove(); // 安全删除
}
}
// 结果:["a", "b", "c"]
</string></string>
注意边界和替代方案
Iterator.remove() 只能删除当前元素,不能跳着删;也不支持添加元素。如果逻辑复杂(如需根据下标操作、批量删多个、或要保留原集合),可考虑:
- 收集待删元素,遍历完再统一调
list.removeAll(toRemove) - JDK 8+ 用
list.removeIf(predicate)(底层仍基于 Iterator) - 反向 for 循环(
for (int i = list.size()-1; i >= 0; i--)),适合按索引判断的场景










