This question already has an answer here:
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
You are not permitted to mutate a list while you are iterating over it. Your
l.remove(j)
causes the listl
to change, but you're inside afor (Integer j : l)
loop.For this you need to use iterator
I used it to add data in database..Hope it helps