java.util.ConcurrentModificationException无法修复

时间:2014-04-06 19:37:56

标签: java arraylist lwjgl

public Game() {
        gameState = OVERWORLD;

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

        battleObjects = new ArrayList<GameObject>();
        battleRemove = 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 update() {
            if (gameState == BATTLE) {
                for (GameObject i : battleObjects) {
                    if (!i.isRemoved())
                        i.update();
                    else
                        battleRemove.add(i);
                }
            }
            else {
                for (GameObject i : objects) {
                    if (!i.isRemoved())
                        i.update();
                    else
                        remove.add(i);
                }
            }
        }

        public void render() {
            if (gameState == BATTLE) {
                for (GameObject i : battleObjects)
                        i.render();
            }
            else {
                for (GameObject i : objects)
                    i.render();
            }
        }

        public static void createNewBattle(Player p, Monster m) {
            battleObjects.add(p);
            battleObjects.add(m);

            gameState = BATTLE;
        }

我完全明白为什么会发生这种情况,但我不能为我的生活找到解决问题的方法......任何人都可以帮助我吗???我在这里坐了好几个小时试图找到另一种方法。我想到的只是用战斗物体创建一个阵列。

1 个答案:

答案 0 :(得分:0)

修改集合的唯一安全方法是使用迭代器中的remove方法,因此使用迭代器而不是每个迭代器,你就可以了: Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop