-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 
1
  • 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... Commented Aug 31, 2013 at 11:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

one question, is not the for each loop is using iterator beneath it
@Naroji: Yes, but the l.remove(j) is not using that iterator, which causes the exception you observed.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.