java+ ConcurrentModificationException forEach(enha

2019-09-21 15:29发布

I am not able to understand the reason, why the below code is throwing CME, even when this is run as single thread application

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


    }
}

Reason:(after going through the answer and other links)

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条回答
孤傲高冷的网名
2楼-- · 2019-09-21 15:45

You are not permitted to mutate a list while you are iterating over it. Your l.remove(j) causes the list l to change, but you're inside a for (Integer j : l) loop.

查看更多
SAY GOODBYE
3楼-- · 2019-09-21 16:03

For this you need to use iterator

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

                    ProfileModel model = it.next();

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

I used it to add data in database..Hope it helps

查看更多
登录 后发表回答