gpt4 book ai didi

java - 带有 vector 和 clear() 的 ConcurrentModificationException

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:16:35 24 4
gpt4 key购买 nike

我有一个非常简单的代码片段,它填充一个 vector ,遍历它,然后清除它。这基本上是我在原则上尝试的:

vector v = new Vector();
v.add(1);
v.add(2);
v.add(3);
ListIterator iter = v.listIterator();

while (iter.hasNext()) {
System.out.println(iter.next());
}

v.clear()

但是我得到一个 ConcurrentModificationException。

通过阅读这篇文章,显然以某种方式使用“同步”是解决方案。但我看到了几种不同的方法,想知道在我的案例中解决这个问题的最好、最简单的方法是什么(不涉及显式线程)?

最佳答案

如果不涉及线程,则可能是您发布的示例不完整。

ConcurrentModificationException如果您在迭代集合时修改集合,就会发生这种情况。

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception.

Vector.listIterator() 的文档明确指出:

Note that the list iterator returned by this implementation will throw an UnsupportedOperationException in response to its remove, set and add methods unless the list's remove(int), set(int, Object), and add(int, Object) methods are overridden.

(实际上 AbstractList.listIterator(int) 的文档;Vector 没有重新定义它。)

关于java - 带有 vector 和 clear() 的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6045229/

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