[英]ConcurrentModificationException in java even without iteration
Can anyone help me out with this code? 谁能帮我这个代码? It throws a
ConcurrentModificationException
. 它抛出一个
ConcurrentModificationException
。 I do know that while iterating a collection and simultaneously adding or removing elements from it, we get a ConcurrentModificationException
. 我确实知道,在迭代集合并同时从中添加或删除元素时,我们会收到
ConcurrentModificationException
。 But I am not iterating in the first place. 但是我并不是一开始就进行迭代。
import java.util.*;
class Test {
public static void main(String[] args){
ArrayList<String> arr = new ArrayList<String>();
ListIterator<String> itr = arr.listIterator();
arr.add("Hello");
arr.add("hi");
System.out.println(itr.next());
}
}
When you call itr.next()
, you are iterating the list (just not completely). 调用
itr.next()
,您正在迭代列表(只是不完全)。 A foreach loop in Java is really just syntactic sugar for: Java中的foreach循环实际上只是以下方面的语法糖:
Iterator<T> it = list.iterator();
while (it.hasNext()) {
T curr = it.next();
}
When modifying the collection, all existing iterators are invalidated, whether you've used them or not yet. 修改集合时,所有现有的迭代器都会失效,无论您是否使用过它们。 You must obtain a new iterator after modifying the list.
修改列表后,您必须获得一个新的迭代器。
The iterators of ArrayList are failfast means if you are trying to iterate and add/remove elements at the same time, the Iterator or ListIterator will throw ConcurrentModificationException. ArrayList的迭代器是快速失败的,意味着如果您尝试同时迭代和添加/删除元素,则Iterator或ListIterator会抛出ConcurrentModificationException。
itr.next() // this is iterating(going over the ArrayList)
arr.add("Hello");//This statement is adding to the ArrayList during iteration
arr.add("hi");//Again this statement is adding to ArrayList during iteration
This causes the ConcurrentModificationException. 这将导致ConcurrentModificationException。
If you want to iterate as well as modify(add/remove) the collection simulateously use CopyOnWriteArrayList,ConcurrentHashMap. 如果要迭代以及修改(添加/删除)集合,请类似地使用CopyOnWriteArrayList,ConcurrentHashMap。 The iterators of CopyOnWriteArrayList,ConcurrentHashMap are failsafe.
CopyOnWriteArrayList,ConcurrentHashMap的迭代器是故障安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.