[Solved] Why does the following code using Iterator next() and remove() throw ConcurrentModificationException? [duplicate]


There is no problem with your usage of Iterator‘s next() and remove().

Your ConcurrentModificationException is caused by adding elements to the List after creating the Iterator.

You should add elements to the List before the Iterator is created.

Change:

Iterator<Integer> iterator = list.iterator();
Collections.addAll(list, 1, 2, 3, 4, 5);

to:

Collections.addAll(list, 1, 2, 3, 4, 5);
Iterator<Integer> iterator = list.iterator();

and your loop will work fine.

solved Why does the following code using Iterator next() and remove() throw ConcurrentModificationException? [duplicate]