0

I was trying to recreate the start screen of AngryBirds where there are projectiles shooting in the background. I tried slick2d with the following code

public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException {
    for (int a = 0; a < delta; a++) {
        if (pros.size() < 5) {
            pros.add(new MenuProjectile(Images.red[0]));
        }
        pros.iterator().forEachRemaining(p -> {
            if (p.getX() > gc.getWidth() || p.getY() > gc.getHeight()) {
                pros.remove(p);
            } else {
                p.update();
            }
        });
    }
}

And slick2d gives me the error

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.forEachRemaining(ArrayList.java:904)
at startmenu.Menu.update(Menu.java:29)
at org.newdawn.slick.state.StateBasedGame.update(StateBasedGame.java:266)
at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:663)
at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
at state.Angrybird.main(Angrybird.java:29)
Thu Mar 29 21:07:04 SGT 2018 ERROR:Game.update() failure - check the game code.
org.newdawn.slick.SlickException: Game.update() failure - check the game code.
    at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:669)
    at org.newdawn.slick.AppGameContainer.gameLoop(AppGameContainer.java:411)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:321)
    at state.Angrybird.main(Angrybird.java:29)
    enter code here

Supposed that if I use iterators, this error should not be thrown. Please help!

Zhao Yun
  • 13
  • 6
  • Instead of using an ArrayList try with a CopyOnWriteArrayList: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html – Emax Mar 29 '18 at 13:43
  • An iterator is no promise that you can not encounter a ConcurrentModificationException. You could try to keep all elements you want to add or remove in an additional list and after you finished iterating your "first" list you add or remove all elements from the other list. – LOLWTFasdasd asdad Mar 30 '18 at 09:48
  • @LOLWTFasdasdasdad How do I use another list? Do you mean that I clone the list and then add the list on to the original list? But how? Wouldn't that cause ConcurrentModificationException as well? – Zhao Yun Mar 31 '18 at 23:26
  • checkout: https://stackoverflow.com/questions/18448671/how-to-avoid-concurrentmodificationexception-while-removing-elements-from-arr – LOLWTFasdasd asdad Apr 03 '18 at 10:15

0 Answers0