-2

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 
lowLatency
  • 5,534
  • 12
  • 44
  • 70
  • You're removing an item from a list while you're iterating over it, but not performing the removal using `Iterator.remove`. There are lots of duplicates of this - I'll try to find one... – Jon Skeet Aug 31 '13 at 11:22

2 Answers2

1

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

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

Snehal Poyrekar
  • 735
  • 5
  • 17