参见英文答案 >
How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList16个
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class MyList {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("S1");
al.add("S2");
al.add("S3");
al.add("S4");
Iterator<String> lir = al.iterator();
while (lir.hasNext()) {
System.out.println(lir.next());
}
al.add(2,"inserted");
while (lir.hasNext()) {
System.out.println(lir.next());
}
}
}
特定的代码会引发错误:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(UnkNown Source)
at java.util.ArrayList$Itr.next(UnkNown Source)
at collections.MyList.main(MyList.java:32)
解决方法
这是因为在创建Iterator之后修改了数组列表.
The iterators returned by this ArrayList’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.
Documentation
Iterator<String> lir = al.iterator(); // Iterator created
while (lir.hasNext())
System.out.println(lir.next());
al.add(2,"inserted"); // List is modified here
while (lir.hasNext())
System.out.println(lir.next());// Again it try to access list
你应该在这里做什么在修改后创建新的迭代器对象.
...
al.add(2,"inserted");
lir = al.iterator();
while (lir.hasNext())
System.out.println(lir.next());