You cannot modify the collection
you are iterating on. That might throw a ConcurrentModificationException
. Though it might work sometimes, but it is not guaranteed to work everytime.
If you want to add, or remove something from your list, you need to use an Iterator
, or ListIterator
for your list. And use ListIterator#add
method to add anything in your list. Even if in your iterator
, if you try to use List.add
or List.remove
, you will get that exception, because that doesn’t make any difference. You should use the methods of iterator
.
See these posts to understand how to use it: –