Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I have an ArrayList that I want to iterate over. While iterating over it I have to remove elements at the same time. Obviously this throws a java.util.ConcurrentModificationException.

What is the best practice to handle this problem? Should I clone the list first?

I remove the elements not in the loop itself but another part of the code.

My code looks like this:

public class Test() {

    private ArrayList<A> abc = new ArrayList<A>();

    public void doStuff() {

        for (A a : abc) 

        a.doSomething();

    }

    public void removeA(A a) {

        abc.remove(a);

    }

}

a.doSomething might call Test.removeA();

1 Answer

0 votes
by (46k points)

Two options:

  • Create a list of values you wish to remove, adding to that list within the loop, then call originalList.removeAll(valuesToRemove) at the end
  • Use the remove() method on the iterator itself. Note that this means you can't use the enhanced for loop.

As an example of the second option, removing any strings with a length greater than 5 from a list:

List<String> list = new ArrayList<String>();

...

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {

    String value = iterator.next();

    if (value.length() > 5) {

        iterator.remove();

    }

}

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...