You cannot remove an item from the collection directly while iterating through the elements as this will cause a ConcurrentModificationException
. Iterator.remove()
is the accepted safe way to modify a collection during iteration. To avoid seeing an IllegalStateException
, make sure to call Iterator.next()
:
while (itr.hasNext()) {
itr.next();
itr.remove();
}
or as you simply wish to remove all elements in the Collection
, you could use:
flights.clear();
See: Efficient equivalent for removing elements while iterating the Collection