【发布时间】:2022-01-12 15:45:42
【问题描述】:
我有一个复杂对象的arrayList Box。我需要将这些 Boxes 的特定元素移动到 arrayList 的最后一个位置,并删除原始元素,如图所示:
我的代码是这样的,但我得到这个错误:ConcurrentModificationException
for (Box i : boxes) { //where boxes is the arrayList
if (i.mouseOver()) { //does the swapping I need if the mouse is over the box
Box copy=i;
boxes.remove(i); //these 3 lines are where I think the mistake is
boxes.add(copy);
}
}
【问题讨论】:
-
问题似乎是您正在尝试修改您正在迭代的
Collection。您必须创建一个新的Collection并对其进行修改。 -
永远不要使用 for-each 循环来修改 Java 列表!我建议你看看this request,它解释了你的问题及其解决方案