在列表中,添加或删除被视为修改。在你的情况下,你做了
5 修改(添加)。
“for each”循环的工作原理如下,
1.It gets the iterator.
2.Checks for hasNext().
public boolean hasNext()
{
return cursor != size(); // cursor is zero initially.
}
3.如果为true,则使用next()获取下一个元素。
public E next()
{
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
final void checkForComodification()
{
// Initially modCount = expectedModCount (our case 5)
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
重复步骤 2 和 3 直到 hasNext() 返回 false。
如果我们从列表中删除一个元素,它的大小会减小,而 modCount 会增加。
如果我们在迭代时移除一个元素,modCount != expectedModCount 会得到满足
并抛出 ConcurrentModificationException。
但是删除倒数第二个对象很奇怪。让我们看看它在您的情况下是如何工作的。
最初,
cursor = 0 size = 5 --> hasNext() 成功并且 next() 也成功
无一例外。
cursor = 1 size = 5 --> hasNext() 成功并且 next() 也成功
无一例外。
cursor = 2 size = 5 --> hasNext() 成功并且 next() 也成功
无一例外。
cursor = 3 size = 5 --> hasNext() 成功并且 next() 也成功
毫无例外。
在您的情况下,当您删除 'd' 时,大小会减小到 4。
cursor = 4 size = 4 --> hasNext() 不成功,next() 是
跳过。
在其他情况下,ConcurrentModificationException 将作为 modCount != expectedModCount 抛出。
在这种情况下,不会进行此检查。
如果您尝试在迭代时打印元素,则只会打印四个条目。最后一个元素被跳过。
希望我说清楚了。