Sobes.tech
Junior — Middle

What specific exception occurs if you modify the contents of a collection while iterating over it with an iterator?

sobes.tech AI

Answer from AI

In Java, modifying the contents of a collection during iteration with an iterator causes a ConcurrentModificationException.

This happens because most collections in Java implement fail-fast iterators, which monitor changes to the collection outside of the iterator and throw this exception when such changes are detected.

Example:

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String item : list) {
    if (item.equals("b")) {
        list.remove(item); // will cause ConcurrentModificationException
    }
}

To avoid this, use the iterator's methods to remove elements:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("b")) {
        iterator.remove(); // safe removal
    }
}
What specific exception occurs if you modify the… - sobes.tech