Friday, 6 April 2012

Safely Removing an Element While Iterating a List

If you want to remove an element while you're iterating a Java ArrayList then you have some problems.  First off, if you use an iterator then the list will most likely throw a ConcurrentModificationException.  If you use a classic style for loop then when you remove an element the list will no longer be the same size or have it's other elements at the same position as when you started iterating which might cause an error, logical or otherwise.

The simplest way to do this is to iterate backwards over the list.  This means when you remove an element, the other elements will not get reordered.  The method below demonstrates:

    public void iterateBackwards()
        List list = new ArrayList(Arrays.asList(1,2,3,4,5));
        for (int i = list.size() - 1; i >= 0; --i)

This prints....