Wednesday, June 9, 2010

Neater Item Removal

I stumbled apon a bit of code today, this removes items in a list and doesn't get a
java.util.ConcurrentModificationException, but it is pretty ugly.

List< Item > newItems = new LinkedList< Item >();

        for (Item item : items) {
            if (item.isAType() ) {
                newItems.add(item);
            }
        }
        items = new LinkedList< Item >();
        items.addAll(newItems);

As Part of reading that "5 Things you didn't know" series from IBM mentioned in a previous blog entry.

A much neater way is using the remove() method on an Iterator:
for (Iterator< Item > itemsIter = items.iterator(); itemsIter.hasNext();) {
     if (itemsIter.next().isAType()) {
  itemsIter.remove();
     }
 }

1 comment:

Popular Posts

Followers