【问题标题】:Move element of arraylist to last position将arraylist的元素移动到最后一个位置
【发布时间】: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);
 }
}

【问题讨论】:

标签: java arraylist


【解决方案1】:

一旦您修改了boxes(通过删除或添加元素),您将无法继续对其进行迭代。一种避免这种情况的方法是,在您移动要移动的 Box 后,通过 break 退出循环:

for (Box i : boxes) {  //where boxes is the arrayList
    if (i.mouseOver()) {  //does the swapping I need if the mouse is over the box
        // No need to create a new reference
        boxes.remove(i);
        boxes.add(i);
        break;
    }
}

【讨论】:

  • 我认为这会创建ConcurrentModificationException
  • 那你错了,@Turtle。试试看。 CME 来自于在修改列表后尝试继续迭代(这可以避免,但 OP 不会),而不是来自修改本身。
  • 好的,看到了...
【解决方案2】:

您不能在 for-each 循环中删除条目。

for (int i = 0; i < boxes.size(); i++) {
    if (boxes.get(i).mouseOver())
        boxes.add(boxes.remove(i));
}

【讨论】:

  • 这将是一个永无止境的loop
  • @Turtle 不,我测试了它,它工作得很好。
【解决方案3】:

如果java.util.ConcurrentModificationException 是您遇到的错误, 尽量不要使用高级 for 循环,而只使用常规 for 循环。同样在您的代码中,我看到您正在尝试使用实际对象从列表中删除元素。在 Arraylist 中,您只能按索引删除,不能按元素删除。

我认为下面应该可以工作。

for (int i = 0; i < boxes.size(); i++) {
    if (boxes.get(i).mouseOver()) { 
        boxes.add(boxes.remove(i));
    }
}

【讨论】:

    猜你喜欢
    • 2017-02-16
    • 2023-03-03
    • 2022-08-17
    • 1970-01-01
    • 2021-12-26
    • 2017-10-19
    • 2015-03-07
    • 2014-03-18
    • 2023-02-09
    相关资源
    最近更新 更多