In your first example, you are iterating through the list yourself. You must take responsibility for maintaining the state of your iteration if you modify the collection during iteration.
In your second example, the "foreach" loop you are using uses an implicit Iterator
behind the scenes. If you modify the collection yourself with an active Iterator
, you will get a ConcurrentModificationException
.
If you must remove an element while using an Iterator
, then use an explicit Iterator
:
for(Iterator<Object> itr = list.iterator(); itr.hasNext())
{
Object o = itr.next():
if (decideToRemove)
itr.remove();
}
The Iterator
's remove
operation is allowed to remove an element without throwing a ConcurrentModificationException
.