Sobes.tech
Junior — Middle

What potential problems may arise when modifying HashMap during iteration over its elements?

sobes.tech AI

Answer from AI

Modifying a HashMap during iteration (for example, when using an iterator) can cause a ConcurrentModificationException. This occurs because the iterator's internal mechanism records the state of the collection at creation, and any changes (other than those made through the iterator itself) trigger an exception.

Problems that may arise:

  • Data integrity issues during concurrent modifications.
  • A ConcurrentModificationException that interrupts program execution.

To avoid this, you can:

  • Use an iterator and its remove() method to delete elements.
  • Copy keys or values into a separate collection and iterate over it.
  • Use a ConcurrentHashMap, which supports safe modification during iteration.

Example of safely removing elements from a HashMap during iteration:

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    if (entry.getValue() < 0) {
        iterator.remove(); // safe removal
    }
}
What potential problems may arise when modifying… - sobes.tech