加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在ArrayList中插入时java.util.ConcurrentModificationException

发布时间:2020-12-14 05:54:37 所属栏目:Java 来源:网络整理
导读:参见英文答案 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 {
参见英文答案 > 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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读