Start by reading the JavaDoc for Iterator. Does it mention ConcurrentModificationException
anywhere?
Now, read the JavaDoc for ConcurrentModificationException, and note the following (emphasis added):
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
Now look closely at your code. Your while
loop iterates through all elements of the collection (even though the output of your first example doesn't indicate this, which tells me that either you've edited the output or this is not your actual code). At the time you remove the element, there are no more items to iterate, so the second loop should always exit immediately.
So, the conclusion is that the implementers of the list iterator have chosen that to throw that exception even when there are no more elements to iterate, while the implementers of the set iterator have chosen not to. Both cases are completely acceptable given the specifications.