在 ArrayList 中插入时出现 java.util.ConcurrentModificationException

标签 java collections

<分区>

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());

关于在 ArrayList 中插入时出现 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227245/

相关文章:

algorithm - 负载系数0.75是什么意思?

java - Mac OS X - 最后修改日期为 0

java - 如何从哈希表中删除这些值?

c# - 无序无重复的线程安全集合

excel - VBA 对象数据在集合中被覆盖

c# - 如何在 C# 中迭代​​时修改或删除可枚举集合中的项目

java - 在幂计算中使用 int、double 和 long

java - 如何停止在 00 :00 o'clock? 更改日期

java - 如何正确使用 org.apache.commons.codec.digest.Md5Crypt?

java - 如果 Hashtable 和 HashMap 在下面的代码片段中都抛出 ConcurrentModificationException ,那么它们之间有什么区别?