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

java+;ConcurrentModificationException forEach(增强)循环单线程,java,collections,Java,Collections,我无法理解为什么下面的代码会抛出CME,即使它是作为单线程应用程序运行的 import java.util.ArrayList; import java.util.List; public class ConcurrentModification { public static void main(String[] args) { ConcurrentModification con = new ConcurrentModification(); co

我无法理解为什么下面的代码会抛出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);
                }
            }


    }
}

在迭代列表时,不允许对列表进行变异。您的
l.remove(j)
会导致列表
l
发生更改,但您位于(整数j:l)循环的
内。

为此,您需要使用迭代器

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

                    ProfileModel model = it.next();

                    DBModel.addProfile(homeScreenActivity, model, profileId);
                }
for(Iterator it=params[0]。Iterator();it
.hasNext();){
ProfileModel=it.next();
DBModel.addProfile(HomeCreenactivity、model、profileId);
}

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

您在迭代列表时从列表中删除一个项目,但不使用
迭代器执行删除操作。删除
。这有很多重复的地方-我会试着找到一个…一个问题,不是每个循环都在使用下面的迭代器it@Naroji:是的,但是
l.remove(j)
没有使用该迭代器,这会导致您观察到的异常。
 for (Iterator<ProfileModel> it = params[0].iterator(); it
                        .hasNext();) {

                    ProfileModel model = it.next();

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