How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList
Asked Answered
G

25

295

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

Geostatics answered 12/11, 2011 at 13:22 Comment(1)
javacodegeeks.com/2011/05/…Syrian
I
432

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();
    }
}
Impalpable answered 12/11, 2011 at 13:24 Comment(18)
I should have mentioned that i remove the elements in another part of the code and not the loop itself.Calculable
@Roflcoptr: Well it's hard to answer without seeing how the two bits of code interact. Basically, you can't do that. It's not obvious whether cloning the list first would help, without seeing how it all hangs together. Can you give more details in your question?Impalpable
I know that cloning the list would help, but I don't know if it is a good approach. But I'll add some more code.Calculable
@Roflcoptr Are you using more than one thread? If you are looping while removing in code called in the loop, you need to loop over a copy of the list, or use a decreasing index, or use a list which does get CME.Chalco
@Roflcoptr: So could you just pass the iterator down instead? Why does removeA need to remove it directly from the collection? Does removeA even need to know about the rest of the collection? Could it actually just return a boolean to say whether or not it should be removed? Basically, the design of your code is encouraging problems here - calling arbitrary code which you don't control while iterating over a collection which can also be modified by other code is fundamentally problematic.Impalpable
Cloning the list may be the best bet... but presumably doSomething could also add something to the list - how would you want that to be handled? Perhaps doSomething should be indicating that it wants something removed instead?Impalpable
@JonSkeet doSomething() does not add something to the list, just possible remove it. I think cloning is a simple solution, but unfortunately i have a ugly cast then. Or is use a for loops that decrements through the list.Calculable
@Roflcoptr: But what if doSomething() decided to remove a different value from the list? There's a problem of encapsulation here, fundamentally. What's doSomething meant to do? Rather than it being able to remove items directly, could it decide whether or not the value should be removed, and let the iterating code do the removal?Impalpable
@JonSkeet What do you mean by a different value? And why should it be a problem when using clone?Calculable
@JonSkeet: Ok I think I've solved the problem. If I just use a for (int i ....) loop then I don't have this problem..Calculable
@JonSkeet small point: originalList.removeAll() has method signature Collection (rather than more specifically, List). So valuesToRemove could be, for example, a List or a Set.Revegetate
This solution also leads to java.util.ConcurrentModificationException, see https://mcmap.net/q/86499/-how-to-avoid-quot-concurrentmodificationexception-quot-while-removing-elements-from-arraylist-while-iterating-it-duplicate.Teran
@CoolMind: Um, no it doesn't. The answer you've linked to is equivalent to mine - what difference do you think there is?Impalpable
@JonSkeet, you are right, but in my case it raised the exception, but another variant worked. Sorry.Teran
@CoolMind: Without multiple threads, this code should be fine.Impalpable
Thanks! My solution was a variation of option 1: cloned the List, iterated through one, changes made in the second, then return the second.Merrymaker
Cloning the list and make changes on it would work but this is the best option to avoid ConcurrentModificationException ( " Without multiple threads, this code should be fine" ) :-) thanks for share Mr. Skeet.Hungnam
saving life with stack overflow answers since 2011Erysipelas
S
32

From the JavaDocs of the ArrayList

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Sinistrality answered 12/11, 2011 at 13:36 Comment(2)
and where is the answer to the question ?Sulphonate
Like it says, except through the iterator's own remove or add methodsSinistrality
U
29

You are trying to remove value from list in advanced "for loop", which is not possible, even if you apply any trick (which you did in your code). Better way is to code iterator level as other advised here.

I wonder how people have not suggested traditional for loop approach.

for( int i = 0; i < lStringList.size(); i++ )
{
    String lValue = lStringList.get( i );
    if(lValue.equals("_Not_Required"))
    {
         lStringList.remove(lValue);
         i--; 
    }  
}

This works as well.

Unitarianism answered 24/8, 2016 at 10:19 Comment(5)
This is not correct!!! when you remove an element, the next is taking its position and while i increases the next element is not checked in the next iteration. In this case you should go for( int i = lStringList.size(); i>-1; i-- )Applied
Agree! Alternate is to perform i--; in if condition within for loop.Unitarianism
I think this answer was edited to address the issues in the above comments, so as it is now it works fine, at least for me.Consecration
@KiraResari, Yes. I have updated the answer to address the issue.Unitarianism
Thank you. Your answer helped me in solving my problem :)Pasteur
N
18

In Java 8 you can use the Collection Interface and do this by calling the removeIf method:

yourList.removeIf((A a) -> a.value == 2);

More information can be found here

Nightjar answered 5/3, 2017 at 10:54 Comment(2)
in Android, Call requires API level 24 (Android Nougat)Constriction
It can still throw the same exception if called multiple times at once.Knipe
A
12

You should really just iterate back the array in the traditional way

Every time you remove an element from the list, the elements after will be push forward. As long as you don't change elements other than the iterating one, the following code should work.

public class Test(){
    private ArrayList<A> abc = new ArrayList<A>();

    public void doStuff(){
        for(int i = (abc.size() - 1); i >= 0; i--) 
            abc.get(i).doSomething();
    }

    public void removeA(A a){
        abc.remove(a);
    }
}
Armistead answered 22/1, 2017 at 23:27 Comment(0)
M
8

While iterating the list, if you want to remove the element is possible. Let see below my examples,

ArrayList<String>  names = new ArrayList<String>();
        names.add("abc");
        names.add("def");
        names.add("ghi");
        names.add("xyz");

I have the above names of Array list. And i want to remove the "def" name from the above list,

for(String name : names){
    if(name.equals("def")){
        names.remove("def");
    }
}

The above code throws the ConcurrentModificationException exception because you are modifying the list while iterating.

So, to remove the "def" name from Arraylist by doing this way,

Iterator<String> itr = names.iterator();            
while(itr.hasNext()){
    String name = itr.next();
    if(name.equals("def")){
        itr.remove();
    }
}

The above code, through iterator we can remove the "def" name from the Arraylist and try to print the array, you would be see the below output.

Output : [abc, ghi, xyz]

Mortie answered 1/2, 2018 at 8:34 Comment(2)
Else, we can use concurrent list which is available in concurrent package, so that you can perform remove and add operations while iterating. For example see the below code snippet. ArrayList<String> names = new ArrayList<String>(); CopyOnWriteArrayList<String> copyNames = new CopyOnWriteArrayList<String>(names); for(String name : copyNames){ if(name.equals("def")){ copyNames.remove("def"); } }Mortie
CopyOnWriteArrayList gonna be costliest operations.Mortie
P
7

You can also use CopyOnWriteArrayList instead of an ArrayList. This is the latest recommended approach by from JDK 1.5 onwards.

Pardner answered 18/2, 2019 at 12:20 Comment(0)
C
5

Here is an example where I use a different list to add the objects for removal, then afterwards I use stream.foreach to remove elements from original list :

private ObservableList<CustomerTableEntry> customersTableViewItems = FXCollections.observableArrayList();
...
private void removeOutdatedRowsElementsFromCustomerView()
{
    ObjectProperty<TimeStamp> currentTimestamp = new SimpleObjectProperty<>(TimeStamp.getCurrentTime());
    long diff;
    long diffSeconds;
    List<Object> objectsToRemove = new ArrayList<>();
    for(CustomerTableEntry item: customersTableViewItems) {
        diff = currentTimestamp.getValue().getTime() - item.timestamp.getValue().getTime();
        diffSeconds = diff / 1000 % 60;
        if(diffSeconds > 10) {
            // Element has been idle for too long, meaning no communication, hence remove it
            System.out.printf("- Idle element [%s] - will be removed\n", item.getUserName());
            objectsToRemove.add(item);
        }
    }
    objectsToRemove.stream().forEach(o -> customersTableViewItems.remove(o));
}
Counts answered 6/7, 2016 at 7:35 Comment(6)
I think that you're doing extra work executing two loops, in worst case the loops would be of the entire list. Would be simplest and less expensive doing it in only one loop.Orometer
I do not think you can remove object from within first loop, hence the need for extra removal loop, also removal loop is only objects for removal - perhaps you could write an example with only one loop, I would like to see it - thanks @LuisCarlosCounts
As you say with this code you can't remove any element inside the for-loop because it causes the java.util.ConcurrentModificationException exception. However you could use a basic for. Here I write an example using part of your code.Orometer
for(int i = 0; i < customersTableViewItems.size(); i++) { diff = currentTimestamp.getValue().getTime() - customersTableViewItems.get(i).timestamp.getValue().getTime(); diffSeconds = diff / 1000 % 60; if(diffSeconds > 10) { customersTableViewItems.remove(i--); } } Is important i-- because you don't want skip any elment. Also you could use the method removeIf(Predicate<? super E> filter) provided by ArrayList class. Hope this helpOrometer
@LuisCarlos, if this is possible, then why the exception when using the other way? perhaps this is not safe, anyway thanks for your exampleCounts
The exception occurs because in for-loop there as an active reference to iterator of the list. In the normal for, there's not a reference and you have more flexibility to change the data. Hope this helpOrometer
S
5

Do the loop in the normal way, the java.util.ConcurrentModificationException is an error related to the elements that are accessed.

So try:

for(int i = 0; i < list.size(); i++){
    lista.get(i).action();
}
Slaphappy answered 21/7, 2017 at 16:57 Comment(1)
You avoided the java.util.ConcurrentModificationException by not removing anything from the list. Tricky. :) You can not really call this "the normal way" to iterate a list.Diann
B
5

Sometimes old school is best. Just go for a simple for loop but make sure you start at the end of the list otherwise as you remove items you will get out of sync with your index.

List<String> list = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i--) {
  if ("removeMe".equals(list.get(i))) {
    list.remove(i);
  }
}
Buckwheat answered 14/9, 2021 at 14:4 Comment(0)
D
4

One option is to modify the removeA method to this -

public void removeA(A a,Iterator<A> iterator) {
     iterator.remove(a);
     }

But this would mean your doSomething() should be able to pass the iterator to the remove method. Not a very good idea.

Can you do this in two step approach : In the first loop when you iterate over the list , instead of removing the selected elements , mark them as to be deleted. For this , you may simply copy these elements ( shallow copy ) into another List.

Then , once your iteration is done , simply do a removeAll from the first list all elements in the second list.

Declivity answered 12/11, 2011 at 13:54 Comment(3)
Excellent, I used the same approach, although I loop twice. it makes things simple and no concurrent issues with it :)Claimant
I don't see that Iterator has a remove(a) method. The remove() takes no arguments docs.oracle.com/javase/8/docs/api/java/util/Iterator.html what am I missing ?Penance
@Penance is right. I mean how did this even get voted 5 times...Lavoie
D
4

Instead of using For each loop, use normal for loop. for example,the below code removes all the element in the array list without giving java.util.ConcurrentModificationException. You can modify the condition in the loop according to your use case.

for(int i=0; i<abc.size(); i++)  {
       e.remove(i);
 }
Dripps answered 12/3, 2018 at 10:35 Comment(1)
I do not think this works. After removing the element at index 0 the second element becomes the first (index 0). In the next iteration we skip this element and remove the one at index 1. Plus, the original question was not how to remove all elements.Diann
G
4

In my case, the accepted answer is not working, It stops Exception but it causes some inconsistency in my List. The following solution is perfectly working for me.

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

for (String value: list) {
   if (value.length() > 5) { // your condition
       itemsToRemove.add(value);
   }
}
list.removeAll(itemsToRemove);

In this code, I have added the items to remove, in another list and then used list.removeAll method to remove all required items.

Gout answered 26/11, 2019 at 11:21 Comment(0)
H
3

Do somehting simple like this:

for (Object object: (ArrayList<String>) list.clone()) {
    list.remove(object);
}
Harwill answered 10/9, 2016 at 17:58 Comment(0)
D
2

An alternative Java 8 solution using stream:

        theList = theList.stream()
            .filter(element -> !shouldBeRemoved(element))
            .collect(Collectors.toList());

In Java 7 you can use Guava instead:

        theList = FluentIterable.from(theList)
            .filter(new Predicate<String>() {
                @Override
                public boolean apply(String element) {
                    return !shouldBeRemoved(element);
                }
            })
            .toImmutableList();

Note, that the Guava example results in an immutable list which may or may not be what you want.

Diann answered 1/2, 2018 at 7:33 Comment(0)
W
2
for (A a : new ArrayList<>(abc)) {
    a.doSomething();
    abc.remove(a);
}
Wattenberg answered 9/3, 2021 at 15:43 Comment(0)
P
0

"Should I clone the list first?"

That will be the easiest solution, remove from the clone, and copy the clone back after removal.

An example from my rummikub game:

SuppressWarnings("unchecked")
public void removeStones() {
  ArrayList<Stone> clone = (ArrayList<Stone>) stones.clone();
  // remove the stones moved to the table
  for (Stone stone : stones) {
      if (stone.isOnTable()) {
         clone.remove(stone);
      }
  }
  stones = (ArrayList<Stone>) clone.clone();
  sortStones();
}
Purposeful answered 30/4, 2013 at 8:43 Comment(3)
Downvoters should at least leave a comment before downvoting.Longstanding
There is nothing inherently wrong with this answer expect maybe that stones = (...) clone.clone(); is superfluous. Would not stones = clone; do the same?Revegetate
I agree, the second cloning is unnecessary. You can futher simplify this by iterating on the clone and remove elements directly from stones. This way you do not even need the clone variable: for (Stone stone : (ArrayList<Stone>) stones.clone()) {...Diann
P
0

I arrive late I know but I answer this because I think this solution is simple and elegant:

List<String> listFixed = new ArrayList<String>();
List<String> dynamicList = new ArrayList<String>();

public void fillingList() {
    listFixed.add("Andrea");
    listFixed.add("Susana");
    listFixed.add("Oscar");
    listFixed.add("Valeria");
    listFixed.add("Kathy");
    listFixed.add("Laura");
    listFixed.add("Ana");
    listFixed.add("Becker");
    listFixed.add("Abraham");
    dynamicList.addAll(listFixed);
}

public void updatingListFixed() {
    for (String newList : dynamicList) {
        if (!listFixed.contains(newList)) {
            listFixed.add(newList);
        }
    }

    //this is for add elements if you want eraser also 

    String removeRegister="";
    for (String fixedList : listFixed) {
        if (!dynamicList.contains(fixedList)) {
            removeResgister = fixedList;
        }
    }
    fixedList.remove(removeRegister);
}

All this is for updating from one list to other and you can make all from just one list and in method updating you check both list and can eraser or add elements betwen list. This means both list always it same size

Passkey answered 11/9, 2018 at 3:26 Comment(0)
O
0

Use Iterator instead of Array List

Have a set be converted to iterator with type match

And move to the next element and remove

Iterator<Insured> itr = insuredSet.iterator();
while (itr.hasNext()) { 
    itr.next();
    itr.remove();
}

Moving to the next is important here as it should take the index to remove element.

Orlosky answered 14/12, 2018 at 10:10 Comment(0)
I
0

Very important

ConcurrentModificationException can occur during ArrayList<> sorting, if the ArrayList<> sorting method is called at the same time, ie. parallel (asynchronous).

For example from two background Threads, or Thread and UI, but at the same time. This usually happens by accident, if you drop the order of operations somewhere during programming.

Happened to me just now :-)

Inclination answered 7/7, 2023 at 2:17 Comment(0)
P
-1
List<String> list1 = new ArrayList<>();
list1.addAll(OriginalList);

List<String> list2 = new ArrayList<>();
list2.addAll(OriginalList);

This is also an option.

Petulah answered 30/6, 2022 at 1:52 Comment(0)
L
-2

If your goal is to remove all elements from the list, you can iterate over each item, and then call:

list.clear()
Lenhard answered 21/8, 2018 at 6:42 Comment(0)
R
-2

What about of

import java.util.Collections;

List<A> abc = Collections.synchronizedList(new ArrayList<>());
Receivership answered 10/4, 2020 at 6:12 Comment(0)
I
-2

ERROR

There was a mistake when I added to the same list from where I took elements:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    for (i in this) {
        this.add(_fun(i))   <---   ERROR
    }
    return this   <--- ERROR
}

DECISION

Works great when adding to a new list:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    val newList = mutableListOf<T>()   <---   DECISION
    for (i in this) {
        newList.add(_fun(i))   <---   DECISION
    }
    return newList   <---   DECISION
}
Innocent answered 21/11, 2020 at 15:43 Comment(0)
P
-4

Just add a break after your ArrayList.remove(A) statement

Practically answered 9/11, 2018 at 4:18 Comment(1)
Could you please add some explanation?Stage

© 2022 - 2024 — McMap. All rights reserved.