Search code examples
for-loopkotlinconcurrentmodification

I have code with for-loop and I always have got concurrent modification exception and i dont know how to solve it


I am programming a sorting system to school that must split some people into two cars, but I am stuck and I don't know how to continue.

When I delete the second when, it was working. But I need it there so I don't know what to do.

I already tried iterators but I am new in kotlin and it didn't work.

for (firstPeople in firstCar){
                    when {
                        k.contains(firstPeople.toString()) -> secondCar.add(j)
                        // println(secondCar)
                        k.contains(firstPeople.toString()) -> firstCar.add(j)
                        // println(firstCar)
                        else -> when {
                            firstCar.size > secondCar.size -> secondCar.add(j)
                            firstCar.size < secondCar.size -> firstCar.add(j)
                            else -> firstCar.add(j)
                        }
                    }
                }

Error:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at MainKt.main(Main.kt:65)
at MainKt.main(Main.kt)

Thank you so much for the answer.


Solution

  • Looks like you are using and ArrayList. And you are inserting an item in it while iterating via iterator: (firstCar.add(j). Here is what its JavaDoc says:

    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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    It means that you may modify the collection only using the iterator methods, and not directly.

    Try to avoid list modification, or use iterator's add method, or use copy on write collections.