【问题标题】:ConcurrentModificationException in foreach loop even though I don't remove anything from arraylist即使我没有从 arraylist 中删除任何内容,foreach 循环中的 ConcurrentModificationException
【发布时间】:2015-01-10 18:56:24
【问题描述】:

我知道有类似的问题,但我浏览了它们并没有找到答案。

我的代码是单线程的,它不会删除任何东西,也不会在循环期间修改数组列表,只是添加。

代码:

ArrayList<Record> records = helper.get();
System.out.println("Records in arraylist: " + records.size());
    for (Record x : records) {
        System.out.println("Begin");
        Record record = new Record(many parameters);
        System.out.println("Middle");
        records.add(record);
        System.out.println("End");
    }
    System.out.println("Done reading records and inserting them to arrayList");

输出:

Records in arraylist: 1000
Begin
Middle
End
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at Main.Main.main(Main.java:33)
    ... 5 more

【问题讨论】:

    标签: java exception arraylist foreach


    【解决方案1】:
     records.add(record);
    

    您在这一行修改了 ArrayList。

    您可以将 for-each 循环转换为 indexed-for 循环以防止 ConcurrentModificationException,或者您可以创建一个新的 ArrayList 来保存您的记录:

    ArrayList<Record> records = helper.get();
    ArrayList<Record> result = new ArrayList<Record>();
    for (Record x : records) {
        Record record = new Record(many parameters);
        result.add(record);
    }
    

    【讨论】:

      【解决方案2】:
       records.add(record);
      

      在这里你修改你的数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-13
        • 2015-10-06
        • 2017-03-28
        • 2014-03-03
        • 2012-04-06
        • 2011-01-19
        • 1970-01-01
        相关资源
        最近更新 更多