Ernestas Gruodis Ernestas Gruodis - 13 days ago 6
Java Question

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

I'm trying to remove some elements from

ArrayList
while iterating it like this:

for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}


Of course, I get
ConcurrentModificationException
when trying to remove item from the list at the same time when iterating
myArrayList
. Is there some simple solution to do that right?

Answer

Use an Iterator and call remove():

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

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}
Comments