2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Modifying a Collection while iterating using for-each loop

when i  modify(i.e., add or remove an object) from a collection while iterating it using for-each loop its giving ConcurrentModificationException.

how can i avoid it? please suggest


You can  avoid ConcurrentModificationException by using the Iterator.

Use Iterator.remove instead. This is the only safe way to modify a collection during iteration. For more information, see The Collection Interface tutorial.


If you want to be able to both add and remove elements while traversing a collection, use a ListIterator instead.

Answer is