Java - ConcurrentModificationException: Not allow to add an entry in the collection while iterating through it

By xngo on June 23, 2019

You are getting ConcurrentModificationException because you are adding an entry in the collection while looping through the collection. It is not allowed to do that. However, Iterator.remove() is the only safe way to modify a collection during iteration. For more details, see http://stackoverflow.com/questions/9806421/concurrentmodificationexception-when-adding-inside-a-foreach-loop-in-arraylist#answer-9806449.

Check http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add%28E%29

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.