Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

illegalStateException when using ArrayList and iterator

Tags:

java

android

I am creating and removing objects in an asteroid shooting game and only on some occasions it crashes and I get this error:

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): FATAL EXCEPTION: Thread-11

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): java.lang.IllegalStateException

07-16 19:35:05.071: ERROR/AndroidRuntime(3553): at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:69)

This is the code which tests for collision between shots and asteroids:

public void shotAstrCollision(){

    asterItr = asteroids.listIterator();

    while(asterItr.hasNext()){  
        aster = asterItr.next();
        shotItr = shots.listIterator();

        while(shotItr.hasNext()){   
            shot = shotItr.next();
            float shotToAst = (float) Math.sqrt((aster.x + astW/2 - shot.x)*(aster.x + astW/2 - shot.x) + (aster.y + astH/2 - shot.y)*(aster.y + astH/2 - shot.y));
            if (shotToAst < astW/2){
                //asteroid is shot
                aster.power -= shot.power;
                shotItr.remove();
                shotCount--;
                createExplosion(aster.x + astW/2, aster.y + astH/2);
                SoundManager.playSound(1, 1);
                if (aster.power <= 0) {
                    asterItr.remove();
                    astCount--; 
                }else{
                    aster.shotColor = ASTEROID_SHOT_PAINT_FRAMES;
                }
            }   
        }   
    }

}

Do you have any idea where to look for a possible cause of this error?

like image 860
Lumis Avatar asked Feb 26 '26 05:02

Lumis


1 Answers

After an asteroid is shot, you need to break out of the inner loop, where you're iterating over shots. Your code is finding that two different shots hit the same asteroid and trying to remove the same asteroid twice. This could also point to a problem with your collision detection, btw.

like image 133
Ryan Stewart Avatar answered Feb 27 '26 18:02

Ryan Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!