首先要知道的是(如JLS所述)以下增强的for循环:
for (String s : list) { // Do something with s }等效于:
for (Iterator<String> it = list.iterator(); it.hasNext();) { String s = it.next(); // Do something with s }如果查看中的迭代器的实现
AbstractList,您将看到:
hasNext()
不检查并发修改,仅使用大小检查我们是否在列表的末尾:
public boolean hasNext() { return cursor != size(); }- 首先要做的
next()
是调用checkForComodification()
以查看在迭代过程中列表是否被修改:
public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }因此,当您迭代并删除列表的倒数第二个元素时,下一条指令将是对的调用
hasNext(),该调用将返回
false,因为删除一个元素会导致列表的大小减小一倍,并且您的迭代将停止而无需调用
next()并抛出一个
Exception。
顺便说一下,所有这些都只是实现细节,您不应该依赖它,因为它可以更改,并且
it.remove()在迭代时可以从列表中删除元素。



