java.util.ConcurrentModificationException不列出删除错误

时间:2014-04-06 05:05:28

标签: java lwjgl

private ArrayList<GameObject> objects;
    private ArrayList<GameObject> remove;

    private static ArrayList<GameObject> battleObjects;

    private Player player;

    private static int gameState;

    public Game() {
        gameState = OVERWORLD;

        objects = new ArrayList<GameObject>();
        remove = new ArrayList<GameObject>();

        battleObjects = new ArrayList<GameObject>();

        player = new Player(Display.getWidth() / 2 - player.SIZE / 2, Display.getHeight() / 2 - player.SIZE / 2);

        objects.add(player);
        objects.add(new Circle(32, 32, player));
        objects.add(new Imp(300, 100, player));
    }

    public void getInput() {
        player.getInput();
    }

    public void update() {
        if (gameState == BATTLE) {
            for (GameObject i : battleObjects) { //**Error happening here**
                if (!i.isRemoved())
                    i.update();
                else
                    remove.add(i);
            }
        }
        else {
            for (GameObject i : objects) {
                if (!i.isRemoved())
                    i.update();
                else
                    remove.add(i);
            }
        }

        for (GameObject i : remove)
            battleObjects.remove(i);
    }

private ArrayList<GameObject> objects; private ArrayList<GameObject> remove; private static ArrayList<GameObject> battleObjects; private Player player; private static int gameState; public Game() { gameState = OVERWORLD; objects = new ArrayList<GameObject>(); remove = new ArrayList<GameObject>(); battleObjects = new ArrayList<GameObject>(); player = new Player(Display.getWidth() / 2 - player.SIZE / 2, Display.getHeight() / 2 - player.SIZE / 2); objects.add(player); objects.add(new Circle(32, 32, player)); objects.add(new Imp(300, 100, player)); } public void getInput() { player.getInput(); } public void update() { if (gameState == BATTLE) { for (GameObject i : battleObjects) { //**Error happening here** if (!i.isRemoved()) i.update(); else remove.add(i); } } else { for (GameObject i : objects) { if (!i.isRemoved()) i.update(); else remove.add(i); } } for (GameObject i : remove) battleObjects.remove(i); } 它不是一个列表删除问题,因为我使用另一个列表来删除后面的代码,而不是每个循环的代码。我不太清楚为什么会这样。我检查了其他线程,它似乎没有帮助我的情况。

2 个答案:

答案 0 :(得分:3)

您正在创建新的ArrayList,并将要从第一个列表中删除的元素添加到此列表中。但是,您必须了解何时定义arrayList,您只需定义或声明该类型的引用。由于您要将第一个List的元素添加到另一个(浅拷贝),因此两个列表都将在内部指向同一个实例。因此,无论您是否迭代其中一个并从其他相同的内部Collection中删除,您都会获得ConcurrentModificationException

现在你可以创建Iterator的{​​{1}},迭代并删除,或者你可以做

List

答案 1 :(得分:2)

当你在它上面迭代时,你不能删除它的一个元素(迭代时), 创建第二个集合并复制您想要的每个元素。

更新: 第二种方式

你应该使用迭代这个

    ArrayList<Integer> objects = new ArrayList<Integer>();
    Iterator<Integer> itr = objects.iterator();
    while (itr.hasNext()) {
        System.out.println(itr.next());
        itr.remove();
    }