Code Review · Java
Java Code Review: Modifying a Collection While Iterating
Review Java code that removes items from a collection inside an enhanced for-loop.
Code Review Exercise
Review the following code and identify as many issues as you can. Think about correctness, maintainability, readability, and modern Java practices.
List<String> users = new ArrayList<>();
users.add("Alice");
users.add("Bob");
users.add("Charlie");
for (String user : users) {
if (user.startsWith("B")) {
users.remove(user);
}
}What issues do you see before scrolling further?
Review Findings
Issue #1: ConcurrentModificationException
The code modifies the collection while iterating over it using an enhanced for-loop. This can throw ConcurrentModificationException at runtime.
Issue #2: Reliability Problem
The bug may not appear immediately during testing, which makes it dangerous. The code may appear to work until the iterator detects the structural modification.
Issue #3: Maintainability
The intent is simply to remove matching elements from a collection. The current implementation is more error-prone than modern alternatives.
Why This Happens
The enhanced for-loop internally uses an iterator.
When the collection is structurally modified outside that iterator, the iterator detects the change and throws:
ConcurrentModificationExceptionThis is a fail-fast mechanism designed to catch incorrect iteration logic early.
Fixed Version: Iterator
Iterator<String> iterator = users.iterator();
while (iterator.hasNext()) {
String user = iterator.next();
if (user.startsWith("B")) {
iterator.remove();
}
}The iterator's own remove() method keeps the iterator and collection in sync.
Fixed Version: Modern Java
users.removeIf(user -> user.startsWith("B"));This is usually the preferred solution because the intent is obvious and the implementation is safe.
Interview Follow-Ups
Does ConcurrentModificationException mean multiple threads are involved?
No. This exception frequently occurs in a single-threaded program. The name is somewhat misleading.
What operations are considered structural modifications?
Operations such as add(), remove(), and clear() change the structure of the collection and can trigger the fail-fast behavior.
Does updating an object inside the collection trigger ConcurrentModificationException?
Usually no. Modifying the contents of an existing object is different from structurally modifying the collection itself.
When should removeIf() be preferred?
Whenever the goal is simply to remove elements matching a condition. It is shorter, safer, and easier to read.
What Interviewers Expect
A junior reviewer may only notice the exception.
A stronger reviewer often goes further:
- Correctness: ConcurrentModificationException.
- Maintainability: Use removeIf() instead.
- Readability: Intent is clearer with removeIf().
- Modern Java: Prefer higher-level collection operations when appropriate.