-2

我无法理解原因,为什么下面的代码会抛出 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 
4

2 回答 2

1

在迭代列表时,不允许对其进行变异。你l.remove(j)导致列表l改变,但你在一个for (Integer j : l)循环中。

于 2013-08-31T11:22:44.923 回答
0

为此,您需要使用迭代器

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

                    ProfileModel model = it.next();

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

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

于 2013-08-31T11:36:27.167 回答