Sobes.tech
Junior — Middle

What problems can arise if you modify a collection while iterating over it?

sobes.tech AI

Answer from AI

Modifying a collection while iterating over it can lead to several issues:

  • ConcurrentModificationException — in Java, standard collections (like ArrayList, HashSet) throw this exception when they detect structural modification during iteration.
  • Unpredictable behavior — elements may be skipped or processed multiple times if the collection is modified (adding or removing elements) during iteration.

To avoid problems, you can:

  • Use an iterator and its remove() method for safe element removal.
  • Create a copy of the collection for iteration, and apply changes to the original.
  • Use special collections from java.util.concurrent that support safe modification during iteration.

Example of safe element removal from a list:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("removeMe")) {
        iterator.remove();
    }
}