Unit 4 Cycle 2 Day 5: ConcurrentModification in Enhanced For
Share
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.
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.