Java: Efficient Equivalent to Removing while Iterating a Collection
- by Claudiu
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.