Java列表的.remove方法仅适用于每个循环中倒数第二个对象

Java列表的.remove方法仅适用于每个循环中倒数第二个对象,第1张

Java列表的.remove方法仅适用于每个循环中倒数第二个对象

在列表中,添加或删除被视为修改。在您的情况下,您进行了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引发。

在这种情况下,不会进行此检查。

如果您尝试在迭代时打印元素,则只会打印四个条目。最后一个元素被跳过。

希望我说清楚。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5016800.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-15
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存