Java: Efficient Equivalent to Removing while Iterating a Collection

Posted by Claudiu on Stack Overflow See other posts from Stack Overflow or by Claudiu
Published on 2008-10-21T23:23:33Z Indexed on 2010/05/15 20:04 UTC
Read the original article Hit count: 143

Filed under:
|
|

Hello everyone.

We all know you can't do this:

for (Object i : l)
    if (condition(i)) l.remove(i);

ConcurrentModificationException etc... this apparently works sometimes, but not always. Here's some specific code:

public static void main(String[] args)
{
    Collection<Integer> l = new ArrayList<Integer>();
    for (int i=0; i < 10; ++i) {
    l.add(new Integer(4));
    l.add(new Integer(5));
    l.add(new Integer(6));
    }
    for (Integer i : l)
    {
        if (i.intValue() == 5)
            l.remove(i);
    }
    System.out.println(l);
}

This, of course, results in:

Exception in thread "main" java.util.ConcurrentModificationException

...even though multiple threads aren't doing it... Anyway.

What's the best solution to this problem? "Best" here means most time and space efficient (I realize you can't always have both!) I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.

© Stack Overflow or respective owner

Related posts about java

Related posts about collections