gpt4 book ai didi

java - 我可以顺序使用许多 listIterators 来改变或删除 Java 中 ArrayList 中的列表元素吗?

转载 作者:行者123 更新时间:2023-12-01 19:33:27 25 4
gpt4 key购买 nike

我依靠列表迭代器来移动字符列表。这是一个单线程程序,我在 4 种不同的方法中顺序使用 listIterator 对象。每种方法都有相同的设置:

private void myMethod(ArrayList<Integer> input) {
ListIterator<Integer> i = input.listIterator();
while (i.hasNext()) {
Integer in = i.next();
if (in < 10)
i.remove();
else
i.set(in*in); // because its lucky
}
}

使用此模式,在第二个迭代器上将引发以下异常:

java.util.ConcurrentModificationException

但是,查看 javadocs,我在抛出的异常中没有看到此异常,也没有看到完成后关闭迭代器的方法。我是否错误地使用了 listIterator?我必须多次迭代同一个 ArrayList,每次都有条件地删除或改变每个元素。也许有更好的方法来迭代 ArrayList,而 ListIterator 不能最好地解决这个用例。

java docs for ListIterator

最佳答案

这在 ArrayList 中有解释。 javadoc,您在使用 Iterator 时使用 remove()set() 修改列表:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

关于java - 我可以顺序使用许多 listIterators 来改变或删除 Java 中 ArrayList 中的列表元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58685444/

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