A developer wrote a method that uses a for-each loop to iterate over a list of strings and remove elements that match a certain condition. However, the method throws a ConcurrentModificationException at runtime. What is the most likely cause?
Modifying the list directly while iterating with a for-each loop causes ConcurrentModificationException because the iterator is not updated.
Why this answer
Option D is correct because a for-each loop internally uses an Iterator to traverse the list. If the list is structurally modified (e.g., by calling remove() directly on the list) during iteration, the iterator's expected modCount will differ from the actual modCount, triggering a ConcurrentModificationException. This is a fail-fast behavior of the ArrayList and other Collection implementations.
Exam trap
The trap here is that candidates often confuse the ConcurrentModificationException with other exceptions (like UnsupportedOperationException) or mistakenly think the for-each loop itself is the problem, rather than recognizing that direct list modification during iteration is the root cause.
How to eliminate wrong answers
Option A is wrong because iterating over an array with a for-each loop does not involve an Iterator and thus cannot throw a ConcurrentModificationException; arrays are fixed-size and do not support structural modification. Option B is wrong because the for-each loop automatically obtains and initializes the iterator; the exception is not caused by improper initialization but by concurrent modification. Option C is wrong because an unmodifiable list would throw an UnsupportedOperationException if remove() is called, not a ConcurrentModificationException.