« Why not to use register.com | Main | Comcast and their questionable billing practices »

Java Iterators are useful reason number 4231

Spotting code like this you know immediately it was never tested.

   for (String cur : list)
   {
        if(cur.dislike()) 
        {
           list.remove(cur);
        }
   }

What are the odds anyone ever ran this?

Hint: in the java 5 enhanced for-loop the Iterator is hidden hence cannot call remove on it. Calling remove on a list while it's being iterated over will always cause a ConcurrentModificationException.

Comments

Where did you see such awful code? :)

This is easy. The trick is to identify places like listeners being called on an event and during the listener method they try to remove themselves from the event roll.

Now that's a hoop!

Sadly, in the code at work.

I had the listeners thing go very wrong during a demo...

Java 1.5 has my new favorite buddy, CopyOnWriteArrayList. Sure it's not optimal, but it a one line change and works with no fuss. Of course, next year I'll find that someone is adding and removing 10000000 listeners per second to the class. Oh well.

Steve - I actually wrote something about a better implmenetation of such event's listeners collections:

http://javachaos.crazyredpanda.com/?p=129

Enjoy!