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