I understand that when using foreach loops or iterators, and removing elements from a list while iterating through it, it can cause the error by confusing the iterator. however I don't seem to be able to visualize how it can confuse it. And thus Im wondering if someone could explain to me how it can confuse an iterator? Thanks
1List<Integer> l3 = new ArrayList<>();
2 l3.add(0); l3.add(2); l3.add(3); l3.add(5);
3
4 int i = 0;
5 for (int e : l3) {
6 if (e % 2 == 0) l3.remove(i);
7
8 }else{ i++};
I expect this to remove all even numbers and remain behind odd numbers, but i am told this could give a concurrentModificationError.
You are removing an element from the list using
while at the same time, iterating with an iterator here
So the list contents and size are out of sync with the iterator causing the exception to be thrown. You should explicitly create an iterator and use that for removal.
prints
Or without using an iterator or explicit loop, use
removeIf