我有 for-loop 的代码,我总是有并发修改异常,我不知道如何解决它

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

我正在编写一个学校的分类系统,必须将一些人分成两辆车,但我卡住了,我不知道如何继续。

当我删除第二个时,它正在工作。但我需要它,所以我不知道该怎么做。

我已经尝试过迭代器,但我是 kotlin 的新手,但它没有用。

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)
                        }
                    }
                }

错误:

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)

非常感谢您的回答。

看起来您正在使用 ArrayList。您在通过迭代器迭代时在其中插入一个项目:(firstCar.add(j)。这是 its JavaDoc 所说的:

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.

这意味着您只能使用迭代器方法修改集合,而不能直接修改。

尽量避免list修改,或者使用iterator的add方法,或者使用copy on write collections