简体   繁体   中英

Java ArrayList in forLoop out of bounds

for(int i1 = schuss.size()-1; i1 >= 0; i1--){
    for(int i2 = (monster.size()-1) ; i2 >= 0; i2--){
        if(monster.get(i2).getBounding().intersects(schuss.get(i1).getBounding())){
            monster.get(i2).life--;
            if(monster.get(i2).life <= 0){
                    monster.remove(i2);
            }
            schuss.remove(i1);
        }
    }
}

I allways get an Exception and I can't Understand why?

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 19, Size: 19
at java.util.LinkedList.entry(LinkedList.java:365)
at java.util.LinkedList.get(LinkedList.java:315)
at Defender_Pack.GameFrame.update(GameFrame.java:139)
at Defender_Pack.MainMethod.main(MainMethod.java:27)

how can I go through all of them without getting an out of bounds Exception and why do I get one because I thought I only ask for Indexes in bound!

i1 is set to the last element of schuss in the outter loop, but an element is removed in the inner loop. i1 won't be decremented until the inner loop completes, so on the 2nd pass through the inner loop, i1 is now out-of-bounds.

I don't know exactly what you're trying to accomplish, but you should probably move the schuss.remove outside the inner loop:

for(int i1 = schuss.size()-1; i1 >= 0; i1--){
    for(int i2 = (monster.size()-1) ; i2 >= 0; i2--){
        if(monster.get(i2).getBounding().intersects(schuss.get(i1).getBounding())){
            monster.get(i2).life--;
            if(monster.get(i2).life <= 0){
                    monster.remove(i2);
            }

        }
    }
    schuss.remove(i1);
}

Do your removals outside the loop, as suggested in comments above.

List<Schuss> tempSchuss = new ArrayList<Schuss>(schuss);
List<Monster> tempMonster = new ArrayList<Monster>(monster);
for(int i1 = schuss.size()-1; i1 >= 0; i1--){
    for(int i2 = (monster.size()-1) ; i2 >= 0; i2--){
        if(monster.get(i2).getBounding().intersects(schuss.get(i1).getBounding())){
            monster.get(i2).life--;
        if(monster.get(i2).life <= 0){
            tempMonster.remove(i2);
        }
        tempSchuss.remove(i1);
        }
    }
}
schuss = tempSchuss;
monster = tempMonster;

I assumed that you have classes Monster and Schuss

The problem should be with the line:

schuss.remove(i1);

Infact the i1th element is removed while you have not finished with it: the next "monster" inner loop might try to access it.

The fix depends on the aim of your code, but adding a

break;

after the mentioned instruction, could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM