java + ConcurrentModificationException forEach(增强型)循环单线程

时间:2013-08-31 11:21:44

标签: java collections

我无法理解原因,为什么以下代码抛出CME,即使这是作为单线程应用程序运行

import java.util.ArrayList;
import java.util.List;

public class ConcurrentModification {

    public static void main(String[] args) {
        ConcurrentModification con = new ConcurrentModification();
        con.call();
    }

    void call() {
        List<Integer> l = new ArrayList<Integer>();
        for (int i = 0; i <= 10000; i++) {
            l.add(i);
        }

            for (Integer j : l) {
                if (j % 3 == 0) {
                    l.remove(j);
                }
            }


    }
}

原因:(在完成答案和其他链接后)

You are not permitted to mutate a list while you are iterating over it.   
Only Iterator remove's method can be used to delete element from list  
For Each loop is using iterator beneath it  
but l.remove(j) is not using that iterator, which causes the exception 

2 个答案:

答案 0 :(得分:1)

在迭代列表时,不允许改变列表。您的l.remove(j)导致列表l发生变化,但您处于for (Integer j : l)循环内。

答案 1 :(得分:0)

为此你需要使用迭代器

 for (Iterator<ProfileModel> it = params[0].iterator(); it
                        .hasNext();) {

                    ProfileModel model = it.next();

                    DBModel.addProfile(homeScreenActivity, model, profileId);
                }

我用它在数据库中添加数据。希望它有帮助