Skip to content
Advertisement

java.util.ConcurrentModificationException when removing elements from arraylist even with iterators

I’m trying to delete content from two arrayLists when a particular condition is satisfied. But when the condition satisfied I get Concurrent modification error. After searching on internet I saw the solution to fix this using the iterator concept but that also doesn’t work.

Here is the two code variations that I tried: [my code is in Kotlin]

1st variation: instantly get error after removing

JavaScript

2nd variation: works if the items are less than 3 in the arraylist, but if items are 3 or more than 3 I get the same error

JavaScript

Error log:

JavaScript

More info: I am creating a snapchat clone app and I’m using google’s firebase for it everything works perfectly i.e uploading,doenloading,deleting in the firebase. so i don’t think this is a firebase issue

Advertisement

Answer

If you are iterating over a collection using an iterator then you can only modify the collection using iterator’s mutator methods, if you try to modify the collection using collection’s mutator methods (remove,set etc) then iterator throws ConcurrentModificationException, this is known as fail-fast property of iterators.

in your case instead of doing snaps.removeAt(index), you should do iterator.remove()

Please note that iterator.remove removes the last element returned by the iterator. So in order to remove an element you have to call next() method first. For example lets say you wanted to remove first element. to achieve this you will have to do the following.

JavaScript

works if the items are less than 3 in the arraylist, but if items are 3 or more than 3 I get the same error

This is because, the ConcurrentModificationException is thrown by next() method, and because in case of 1 or 2 elements it only gets called once, that to before any modification, so you don’t get any error. In above cases following steps are executed:

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