Monthly Archives: November 2010

Syntactic Sugar

This is one of my favorite quotes responding to criticism about modern programming languages:

“There has been a tendency to dismiss all the new features of C# as ‘syntactic sugar’. If you think this is another example, then I guess you probably feel the same way about assembly language, and feel that there haven’t really been any significant coding innovations since the front panel with toggle switches.”

Source: IanG Blog

Removing while iterating

The context of this post is Java, but the concept applies to other languages as well. (C#, etc).

Have you ever encountered a need to remove elements from a collection while iterating over it? This is not allowed:

for(Foo f : fooList) {
    if(f.bar()) {
        fooList.remove(f);
    }
}

A ConcurrentModificationException will be thrown, since you are attempting to modify a list during iteration. It makes sense; after all, if you remove something, the list is in a new state, and who is to say what the next element is at that point?

There is however a solution, and it involves a commonly used pattern in C++, which is to use an iterator. An iterator provides you with access to the next element in its iteration, as well as access to the original iteration index. This allows you to manipulate whatever list you are iterating over, since your iteration does not rely on its current state, only the state of which the iterator was based on.

Here is the above example reworked:

  for (Iterator iter = fooList.iterator(); iter.hasNext(); Foo f = iter.next()) {
    if(f.bar()) {
      iter.remove();
    }
  }

The .remove() option on the iterator removes the element from the underlying collection, but does not impact the iterator.