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!
Posted by: Aviad Ben Dov | February 17, 2006 05:55 PM
Sadly, in the code at work.
Posted by: kasia | February 17, 2006 06:24 PM
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.
Posted by: Steve | February 22, 2006 01:00 PM
Steve - I actually wrote something about a better implmenetation of such event's listeners collections:
http://javachaos.crazyredpanda.com/?p=129
Enjoy!
Posted by: Aviad Ben Dov | February 22, 2006 04:37 PM