Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? [duplicate]

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?

like image 907
Ernestas Gruodis Avatar asked Aug 26 '13 16:08

Ernestas Gruodis


People also ask

How can you avoid ConcurrentModificationException during the iteration of a collection?

To Avoid ConcurrentModificationException in single-threaded environment. You can use the iterator remove() function to remove the object from underlying collection object. But in this case, you can remove the same object and not any other object from the list.

How do you overcome ConcurrentModificationException?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

Why does iterator remove Do not throw ConcurrentModificationException?

Notice that iterator. remove() doesn't throw an exception by itself because it is able to update both the internal state of itself and the collection. Calling remove() on two iterators of the same instance collection would throw, however, because it would leave one of the iterators in an inconsistent state.


1 Answers

Use an Iterator and call remove():

Iterator<String> iter = myArrayList.iterator();  while (iter.hasNext()) {     String str = iter.next();      if (someCondition)         iter.remove(); } 
like image 157
arshajii Avatar answered Oct 15 '22 23:10

arshajii