Saturday, April 08, 2006

Java for-each vs iterator

Being really happy that in Java 5 the for-each shorthand for loops over collections and the like was introduced, I ran into a stupid pitfall the other day.

With an iterator you can remove an element from the underlying collection using the iterator.remove() method, like this

Iterator it = somelist.iterator();
while (it.hasNext())
{
   MyObject o = it.next();
   // o.dosomething();
   it.remove(); // removes the current object from the list
}


This is no longer visible if you change from iterator to for-each:

for (MyObject o : somelist)
{
   // o.dosomething();
   somelist.remove(o); // removes o from the list
}

Since the iterator is not exposed to your code, the pitfall is to remove the object directly from the collection...

This will cause a ConcurrentModificationException... not a nice thing to do. But actually its quite clear and obvious.

Afterwards...

No comments: