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:
- 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
}
}
-
Use collections from the
java.util.concurrentpackage, such asCopyOnWriteArrayList, which allows safe modification of the collection during iteration, but with some performance limitations. -
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.