JDK: Sun 1.5.0_16
Also tried on jrockit81sp5_142_08
Just for curiosity, I was trying out the following code snippet:
I expect java.util.ConcurrentModificationException to be thrown and this code works as expected.
But when I try the same code with the second-last element ("Four" in this case), I do not get this exception. I get java.util.ConcurrentModificationException for "Five". I was expecting the behaviour to be consistent and since the list had been structurally modified, as per the specs, I should have got java.util.ConcurrentModificationException when I remove "Four" as well.
The main thing you missed is this note in the API:
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
In short, CME is never guaranteed to be thrown. It may be thrown. I would say, there's a very good chance it will be thrown, if you're doing concurrent modifications, but don't count on it.
If you analyze the behavior carefully, you will find that this particular behavior occurs when you remove the next-to-last element of the list you're iterating through. By doing this, you "fool" the Iterator into thinking that the list has no more elements (since you're on the fourth element, and the size of the list is four - you must be done. So you finish the loop without another call to next(), and next() is the method that would have thrown the exception.