有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用迭代器时的java ConcurrentModificationException<Node>

我试图删除带有JavaFX矩形的JavaFXGridPane的,但我没有找到方法,只能将上面的正方形复制到下面的一行。这是我的代码,但它一直抛出ConcurrentModificationAcception

static void copyAbove(int rowToBeDisappear, GridPane mainGrid) {
        for (int y = (rowToBeDisappear-1); 0 <= y ; y--) {
            for (int x = 0; x <= 9; x++) {
                Iterator<Node> iterator = mainGrid.getChildren().iterator();
                while (iterator.hasNext()) {
                    Node sqr = iterator.next();
                    if (sqr == getSqrByIndex(x,y,mainGrid)) {
                        iterator.remove();
                        mainGrid.add(sqr,x,(y+1));
                    }
                }
            }
        }
    }

错误

Caused by: java.util.ConcurrentModificationException at com.sun.javafx.collections.VetoableListDecorator$VetoableIteratorDecorator.checkForComodification(VetoableListDecorator.java:714) at com.sun.javafx.collections.VetoableListDecorator$VetoableIteratorDecorator.hasNext(VetoableListDecorator.java:682) at Main.copyAbove(Main.java:%local_code_row_nvm_this%)


共 (2) 个答案

  1. # 1 楼答案

    感谢@Slaw指出了我解决方案中的缺陷

    不能同时迭代迭代器和修改其支持集合(除非通过该迭代器的remove方法)。将您希望对集合所做的任何结构更改存储到临时集合中,然后在迭代后执行这些更改

    如果给定一个x和一个y,保证getSqrByIndex()最多返回一个Node,则以下代码将不会导致CME:

    Node node = null;
    
    Iterator<Node> iterator = mainGrid.getChildren().iterator();
    while (iterator.hasNext()) {
        Node sqr = iterator.next();
        if (sqr == getSqrByIndex(x,y,mainGrid)) {
            node = sqr;
        }
    }
    
    if (node != null) {
        mainGrid.getChildren().remove(node);
        mainGrid.add(node, x, y + 1);
    }
    
    
  2. # 2 楼答案

    我是个十足的白痴,对这一点还不熟悉,所以这可能是错误的,但为什么不使用for()循环而不是while()?我相信它将它保持在范围内,以便您可以调用迭代器。删除()此外,它可能会抛出该错误,因为您在迭代的同时将对象添加到迭代器中。我将尝试分离添加和删除对象的点