Junior — Middle
What happens if you prevent the removal of elements from a collection during its iteration?
sobes.tech AI
Answer from AI
If during iteration over a collection in Java you try to remove elements directly from it (for example, through a collection method), it will lead to a ConcurrentModificationException. This happens because the iterator tracks changes to the collection, and removing elements outside of its methods breaks the integrity of the iteration.
The correct way to remove elements during iteration is to use the remove() method of the iterator itself:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (condition) {
iterator.remove(); // safe removal
}
}
Thus, removal will not disrupt the iterator's operation and no exception will occur.