Middle
How will an instantiated iterator for a collection behave if the collection.remove() method is called?
sobes.tech AI
Answer from AI
Calling collection.remove() during iteration with an instantiated iterator can lead to a ConcurrentModificationException.
This happens because the iterator usually does not know about changes made directly to the underlying collection from outside the iterator. The iterator maintains internal state (e.g., the index of the current element), which becomes invalid if the collection is modified outside of the iterator's methods (iterator.remove()).
Some collection implementations are "fail-fast" and will throw a ConcurrentModificationException upon detecting such changes to prevent unpredictable behavior.
The only safe way to modify a collection during iteration is to use the iterator.remove() method.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorModificationExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if ("B".equals(element)) {
// This will cause a ConcurrentModificationException
// list.remove(element);
// This is a safe way to remove
iterator.remove();
}
}
System.out.println(list);
}
}