← 中文资源

简体中文版本

fail-fast 迭代器的安全删除

for-each 循环里直接 remove 会触发 ConcurrentModificationException:Iterator.remove 与 removeIf 通过游标同步删除,列表结构不会被改坏。

阅读英文原文

实现说明

活动部件是类 CartCleanup和函数 main。 这个示例中仅有的重复出现在 for (String item : cart) 里。

使用要点

  • 跑完文件,输出里会留下标记——after iterator.remove:、after removeIf:。

常见问题

运行「fail-fast 迭代器的安全删除」会打印什么?

运行文件本身,after iterator.remove:、after removeIf: 这些前缀各对应一段演示逻辑。

核心语句

cart.removeIf(item -> item.startsWith("expired"));
cart.add("expired-cheese");
cart.remove(item);

代码示例

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;

public class CartCleanup {

    public static void main(String[] args) {
        List<String> cart = new ArrayList<>(
                List.of("apple", "expired-yogurt", "bread", "expired-milk"));

        // Removing directly inside for-each: modCount mismatches and the next next() throws
        try {
            for (String item : cart) {
                if (item.startsWith("expired")) {
                    cart.remove(item);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("for-each remove -> ConcurrentModificationException");
        }

        // Iterator.remove keeps deletion in sync with the cursor, so no fail-fast
        for (Iterator<String> it = cart.iterator(); it.hasNext(); ) {
            if (it.next().startsWith("expired")) {
                it.remove();
            }
        }
        System.out.println("after iterator.remove: " + cart);

        // removeIf wraps the same mechanism in a method
        cart.add("expired-cheese");
        cart.removeIf(item -> item.startsWith("expired"));
        System.out.println("after removeIf: " + cart);
    }
}