当前位置: 动力学知识库 > 问答 > 编程问答 >

arrays - 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!

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: