Fail Fast Iterator Safe Removal

Removing from an ArrayList inside for-each trips ConcurrentModificationException; Iterator.remove and removeIf delete through the cursor safely.

JavaData Integrity

Code

snippet
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);
    }
}

How the snippet works

Everything happens inside the class CartCleanup and the function main.

The one repetition in this snippet is the loop for (String item : cart).

Applying it

The demo output is labeled (after iterator.remove:, after removeIf:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Fail Fast Iterator Safe Removal print when run?
Invoke the file as-is — the `after iterator.remove:`, `after removeIf:` prefixes identify which step printed each line.