Sobes.tech
Junior — Middle

How can you safely iterate over a collection while modifying it at the same time?

sobes.tech AI

Answer from AI

In Java, when iterating over a collection and modifying it simultaneously, it is important to avoid ConcurrentModificationException. There are several approaches:

  1. Use an iterator and its remove() method to delete elements during iteration:
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (condition) {
        iterator.remove(); // safe removal
    }
}
  1. Use collections from the java.util.concurrent package, such as CopyOnWriteArrayList, which allows safe modification of the collection during iteration, but with some performance limitations.

  2. Collect elements to be removed or added into a separate list, and after iteration, apply the changes.

Thus, safely modifying a collection during iteration can be done through an iterator or special thread-safe collections.

How can you safely iterate over a collection while… - sobes.tech