Search code examples
javaiteratorconcurrentmodificationnosuchelementexception

Concurrent modification when next() has exhausted elements


Been reading up on Iterators recently. Suppose that we want to build a fail-fast Iterator for a given container class. At some point in time, the following code has executed;

Iterator<Object> it = myContainer.iterator();
while(it.hasNext())
    System.out.println(it.next());

Then, we perform a modification on myContainer, using, say, a method called remove(int index):

myContainer.remove(2);      // Assume at least 3 elements contained

If it.next() is called now, and based on the official docs, should we throw an instance of ConcurrentModificationException, or NoSuchElementException? Perhaps more importantly, is this in any way inferrable from the official docs?


Solution

  • You should throw a ConcurrentModificationException. A NoSuchElementException indicates there are no more elements in the iterator. When you encounter a concurrent modification, it always overrules the NoSuchElementException. At least that how the Arraylistand LinkedList are doing it.