In my code:
Collection<String> c = new ArrayList<>();
Iterator<String> it = c.iterator();
c.add("Hello");
System.out.println(it.next());
Exception occures, because my collection changed after iterator created.
But what about in this code:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Integer integer : list) { // Exception is here
if (integer.equals(2)) {
list.remove(integer);
}
}
Why exception occured?
In second code, i did changes in my collection before for-each loop.
In the second loop, it's the same reason - you are removing an element from the list.
To remove elements from a List
while looping through it, either use standard old-fashioned for loops:
for(int i=0;i<list.size();i++) {
and remove list items inside that loop or use a ListIterator
to iterate over the list.