使用Iterator< Node>时发生ConcurrentModificationException [英] ConcurrentModificationException while using Iterator<Node>

查看:104
本文介绍了使用Iterator< Node>时发生ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用JavaFX矩形删除的JavaFX GridPane,但我没有办法删除,只能将上面的正方形复制到下面的一行.这是我执行此操作的代码,但会不断抛出 ConcurrentModificationAcception .

I was trying to delete a row of JavaFX GridPane with JavaFX Rectangles and I found no way to do so but copying the squares above to one row below. Here is my code to do that but it keeps throwing 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));
                    }
                }
            }
        }
    }

错误

由以下原因引起:java.util.ConcurrentModificationException 在com.sun.javafx.collections.VetoableListDecorator $ VetoableIteratorDecorator.checkForComodification(VetoableListDecorator.java:714)处 在com.sun.javafx.collections.VetoableListDecorator $ VetoableIteratorDecorator.hasNext(VetoableListDecorator.java:682) 在Main.copyAbove(Main.java:%local_code_row_nvm_this%)

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

推荐答案

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

Thanks to @Slaw for pointing out the flaw in my solution.

您不能同时迭代迭代器并修改其后备集合(通过该迭代器的remove方法除外).将您希望对集合进行的所有结构更改存储到临时集合中,然后在迭代后执行.

You can't iterate an iterator and modify its backing collection (except through that iterator's remove method) at the same time. Store any structural changes you'd like done on the collection to a temporary collection, then perform them after iterating.

如果在给定xy的情况下保证getSqrByIndex()最多返回一个Node,则以下代码将不会导致CME:

If getSqrByIndex() is guaranteed to return at most one Node given an x and a y, then the following code will not cause CMEs:

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

这篇关于使用Iterator&lt; Node&gt;时发生ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆