简体   繁体   English

在Java中迭代问题时删除

[英]Removing while iterating issues in java

I want to implement a method attack that works like this: every warrior from my troop attacks an warrior chosen randomly from another troop. 我想实施一种方法攻击,如下所示:我部队中的每个战士都会攻击从另一个部队中随机选择的战士。 If the attacked warrior dies it must be removed from the troop. 如果被攻击的战士死亡,则必须将其从部队中撤出。 With the method that i tried i get the error for the random number: 使用我尝试的方法,我得到了随机数错误:

 java.lang.IllegalArgumentException: n must be positive

The troop is a List <Creature> warriors; 部队是一个名单<Creature>战士。 I think that i am not doing the remove correctly, because otherwise i should not have that error. 我认为我没有正确执行删除操作,因为否则我应该不会遇到该错误。

public void atac(Troop opponentTroop){
        for(Creature f : warriors){
            Creature c = getOpponent(opponentTroop);
            f.atac(c);
            ListIterator<Creature> iterator = opponentTroop.warriors.listIterator();
            while(iterator.hasNext()){
                c = iterator.next();
                if(c.isDead()){
                    iterator.remove();                  
                }
            }   

        }       
    }


private Creature getOpponent(Troop opponent){
        int x = rand.getRandomArrayIndex(opponent.warriors.size());
        return opponent.warriors.get(x);
}

Removing the entry invalidates the iterator. 删除条目会使迭代器无效。 You need to save it, you could do something like this: 您需要保存它,可以执行以下操作:

while(iterator.hasNext()) {
    c = iterator.next();
    if(c.isDead()) {
        // Make a temporary iterator
        ListIterator<Creature> toDelete= c;
        // Step the regular one
        c = iterator.next();
        // Remove
        toDelete.remove();                  
    }
}   

Also, make sure int x = rand.getRandomArrayIndex(opponent.warriors.size()); 另外,请确保int x = rand.getRandomArrayIndex(opponent.warriors.size()); never goes beyond the last index (which is the number of entries minus one . 从不超过最后一个索引(即条目数减去1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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