Sobes.tech
Junior — Middle

Почему удаление элементов из коллекции внутри цикла for-each может привести к ошибкам или некорректному поведению программы?

sobes.tech AI

Answer from AI

Removing elements from a collection inside a for-each loop (for example, in Java) can lead to errors or incorrect behavior because the collection should not be structurally modified during iteration.

Reasons:

  • The iterator used in the for-each loop does not expect the collection's size to change, and removing elements can throw a ConcurrentModificationException.
  • Even if no exception occurs, modifying the collection can cause elements to be skipped or processed multiple times.

The correct way to remove elements during iteration is to use an explicit iterator and its remove() method:

Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (condition_for_removal) {
        iterator.remove();
    }
}

This way, removal is safe, without disrupting the internal state of the collection or causing errors.