سؤال

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

Its not a list removal problem because I'm using another list to remove objects later in code not in the same for each loop. I'm not quite sure why this has happened. I have checked other threads and it doesn't seem to help my situation.

هل كانت مفيدة؟

المحلول

You are creating a new ArrayList and adding elements to be removed from 1st list to this list. But you must understand when you define a array or List you merely define or declares references of that type. Since you are adding elements of first List to the other(shallow copy), both Lists will have elements pointing to same instance internally. So no matter if you iterate on one and remove from other same internal Collection gets modified and hence you get the ConcurrentModificationException.

So now you can either create Iterator of the List, iterate and remove or you can do

battleObjects.removeAll(remove);

نصائح أخرى

you can't remove an element of a collection when you are iterating on it(while iteration), create second collection and copy each element you want on it .

Update : second way

you should use iteration lik this

    ArrayList<Integer> objects = new ArrayList<Integer>();
    Iterator<Integer> itr = objects.iterator();
    while (itr.hasNext()) {
        System.out.println(itr.next());
        itr.remove();
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top