gpt4 book ai didi

java - 如果使用 LinkedList add 方法修改底层列表,iterator.next 是否也会被修改?

转载 作者:行者123 更新时间:2023-11-30 05:58:25 24 4
gpt4 key购买 nike

intLinkList = 2, 4, 6, 8, 10
Iterator itr = intLinkList.iterator()

假设迭代器正在迭代并且当前指向整数 6。

itr current item  = 6
itr previous item = 4
itr next item = 8

当 itr 当前指向整数 6 时,我使用链接列表的 add(Object obj, int index) 方法在整数 6 和整数 8 之间添加/插入整数 7。

我知道此 itr 实例在此修改后无效,因为基础列表已被修改,因此 modCount != ExpectedModCount。

我的问题是这样的:使用 LinkedList 的 add 方法进行修改是否会更改 itr.next 指向的项目?我做了一些阅读,我知道这会抛出 ConcurrentModificationException。但这并不能回答我的问题,如果迭代器迭代时底层列表被修改,itr.next 项是否被修改。

最佳答案

Does the modification using LinkedList's add method change the item the itr.next is pointing at?

没有。

调用 LinkedListadd 不会改变 Iterator 状态中的任何内容。调用 Iteratornext() 方法后,在迭代器计算要返回的下一个元素之前,它将检查修改并抛出 ConcurrentModificationException .

以下是相关代码,来自 AbstractList$Itr:

    public E next() {
checkForComodification(); // will throw ConcurrentModificationException
// before the Iterator's state is changed
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}

关于java - 如果使用 LinkedList add 方法修改底层列表,iterator.next 是否也会被修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52736558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com