Intellipaat Back

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

I'm trying to remove some elements from an ArrayList while iterating it like this:

for (String str : myArrayList) {

    if (someCondition) {

        myArrayList.remove(str);

    }

}

Of course, I get a ConcurrentModificationException when trying to remove items from the list at the same time when iterating myArrayList. Is there some simple solution to solve this problem?

1 Answer

0 votes
by (46k points)

Try an Iterator and call remove():

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {

   String str = iter.next();

   if (someCondition)

       iter.remove();

}

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...