问题描述
当我执行下面的代码,我得到ConcurrentModificationException
When I execute the following code, I get ConcurrentModificationException
Collection<String> myCollection = Collections.synchronizedList(new ArrayList<String>(10));
myCollection.add("123");
myCollection.add("456");
myCollection.add("789");
for (Iterator it = myCollection.iterator(); it.hasNext();) {
String myObject = (String)it.next();
System.out.println(myObject);
myCollection.remove(myObject);
//it.remove();
}
为什么我得到异常,即使我使用Collections.synchronizedList?
Why am I getting the exception, even though I am using Collections.synchronizedList?
当我将myCollection改为
When I change myCollection to
ConcurrentLinkedQueue<String> myCollection = new ConcurrentLinkedQueue<String>();
我没有这个异常。
如何在java.util.concurrent中的ConcurrentLinkedQueue与Collections.synchronizedList不同?
How is ConcurrentLinkedQueue in java.util.concurrent different from Collections.synchronizedList ?
推荐答案
> List将不提供 Iterator
的新实现。它将使用 synchronized 列表的实现。 的实现
A synchronized List will does not provide a new implementation of Iterator
. It will use the implementation of the synchronized list. The implementation of iterator()
is:
public Iterator<E> iterator() {
return c.iterator(); // Must be manually synched by user!
}
从 ArrayList
:
从 ConcurrentLinkedQueue#iterator
:
两个集合返回的迭代器根据设计不同 。
The iterators returned by the two collections are different by design.
这篇关于Java:在迭代列表时发生ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!