Unit 4 Cycle 2 Day 5: ConcurrentModification in Enhanced For

Unit 4 Advanced (Cycle 2) Day 5 of 28 Advanced

ConcurrentModification in Enhanced For

Section 4.5 — ArrayList Algorithms

Key Concept

Using an enhanced for loop to remove elements from an ArrayList causes a ConcurrentModificationException. The enhanced for loop uses an iterator internally, and modifying the list during iteration invalidates the iterator. The AP exam tests this as an error-spotting question. Safe alternatives: use a standard indexed for loop (traversing backward), or build a separate list of elements to remove and call removeAll() afterward. The enhanced for loop is safe for reading but not for structural modification.

Consider the following code segment.

ArrayList nums = new ArrayList(); nums.add(1); nums.add(2); nums.add(3); for (int n : nums) { nums.add(n * 2); } System.out.println(nums);

What happens when this code executes?

Answer: (C) A ConcurrentModificationException occurs.

Adding to an ArrayList during an enhanced for loop throws ConcurrentModificationException. The iterator detects structural modification.

Why Not the Others?

(A) The exception occurs before this result is achieved.

(B) Elements are not replaced; the code attempts to add.

(D) The exception stops execution before infinite behavior.

Common Mistake

Never add or remove from a collection during an enhanced for loop. Use a standard indexed for loop or build a separate collection.

AP Exam Tip

Enhanced for + structural modification = ConcurrentModificationException. This is a definite AP exam topic.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.