Tuesday, June 4, 2013

Removing elements while Iterating over a Collection ?

Intent here is to check if you are aware of technique of modifying the collection structure while iterating over it. If we call collection.remove() from within the for loop then ConcurrentModificationException will be thrown by the JVM at runtime.


So lets take code snippet the given method
/***Failing Program, Never call Collection.remove(Object) while iterating***/

import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;

public class Test {
    public void removeFromCollection(List marks) {
        for (Integer mark : marks) {
            if (mark < 40)
                marks.remove(mark); ==> Will throw java.util.ConcurrentModificationException
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.removeFromCollection(new ArrayList(asList(10,20,50,60)));
    }
}

Actually, the right way to handle such scenario is to use Iterator to remove the element from the underlying Collection while iterating over it. ConcurrentModificationException is thrown because the for loop internally creates a fail-fast iterator which throws exception whenever it finds any structural modification in the underlying data structure (ArrayList in this case).

The correct implementation for removal method would look something like,
public void removeFromCollection(List marks) {
        for (Iterator iterator = marks.iterator(); iterator.hasNext(); ) {
            Integer mark = iterator.next();
            if (mark < 40)
                iterator.remove();
        }
    }

No comments:

Post a Comment

Your comment will be published after review from moderator