Removing elements while iterating over a Java Collection

Carvia Tech | April 27, 2019 | 2 min read | 55 views | Multithreading and Concurrency


Interviewer’s Intent

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

So lets consider the below naive approach for removing elements from a collection while iterating over it:

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); (1)
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.removeFromCollection(new ArrayList(asList(10,20,50,60)));
    }
}
1 this line will throw java.util.ConcurrentModificationException
ConcurrentModificationException javadocs

It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as <i>fail-fast</i> iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

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 like this:

Correct implementation for removing element
public void removeFromCollection(List marks) {
    for (Iterator iterator = marks.iterator(); iterator.hasNext(); ) {
        Integer mark = iterator.next();
        if (mark < 40)
            iterator.remove();
    }
}

If you are facing this exception in a multi-threading scenario, then better to consider using fail-safe iterators.


Top articles in this category:
  1. Fail-Safe vs Fail-Fast Iterator in Java Collections Framework
  2. What is purpose of Collections.unmodifiableCollection
  3. How will you handle ConcurrentModificationException in Java
  4. Can the keys in HashMap be mutable
  5. Design an Immutable class that has an java.util.Date member
  6. How will you increment each element of an Integer array, using parallel operation
  7. How to implement Thread pool in Java without executor framework



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info