foreach循环中的ConcurrentModificationException,即使我没有从arraylist中删除任何内容

时间:2014-11-13 15:12:49

标签: java exception arraylist foreach

我知道有类似的问题,但我经历过这些问题并没有找到答案。

我的代码是单线程的,它不会删除任何内容或无论如何在循环中修改arraylist,只需添加。

代码:

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

2 个答案:

答案 0 :(得分:0)

 records.add(record);

在这里修改数组。

答案 1 :(得分:0)

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