Skip to content
Advertisement

java.util.ConcurrentModificationException while mutating an object

I am iterating over a List of CustomObject and while doing this iteration, I am mutating this object by adding a tag to tags list of this custom object. I am not adding or removing any CustomObject to or from customObjects (List). I am still getting java.util.ConcurrentModifcationException.

JavaScript

Here is the stack trace:

JavaScript

Does this mean we can get ConcurrentModifcationException even if we just try to modify the object and not remove or add from/to the list/collection?

Advertisement

Answer

First, you are using a List type in the for loop to iterate the elements, so the enhanced for statement is equivalent to a for using an iterator, as mentioned here, because List implements Iterator. Also, it’s obvious from the stack trace.

When using Iterator, you can’t make modifications on the list you are iterating, as mentioned GeeksForGeeks, you will get ConcurrentModificationException.

So, to solve this issue, you can for example implement explicitly the for loop using integers like below:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement