Junior — Middle
What consequences may arise when attempting to modify a collection while iterating over its elements?
sobes.tech AI
Answer from AI
When attempting to modify a collection (for example, adding or removing elements) during its traversal using an iterator in Java, a ConcurrentModificationException usually occurs. This happens because the iterator captures the state of the collection at creation, and any changes outside the iterator's methods are considered incorrect.
To avoid this error, you can:
- Use iterator methods for removing elements (
iterator.remove()), which are safe. - Create a copy of the collection and traverse it, modifying the original.
- Use special collections from
java.util.concurrentthat support safe concurrent modification.
Example of safe element removal during traversal:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (item.equals("removeMe")) {
iterator.remove(); // safely removes the current element
}
}