On Nov 17, 2009, at 11:21 AM, Paul Smaldino wrote:
public Bag findNotPlayed(Bag neighbors){
for(int k = 0; k < neighbors.numObjs; k++){
Agent a = (Agent)neighbors.get(k);
if(a.equals(this) || a == this){
neighbors.removeNondestructively(k);
break;
}
}
int num = neighbors.numObjs;
for(int i=0; i < num; i++){
Agent a = (Agent)neighbors.get(i);
if(a.played)
neighbors.removeNondestructively(i);
}
return neighbors;
}
In the second for loop, when I used i < neighbors.numObj, the method removed
only one of the two agents who had played. When I substituted the local
variable num, I got a IndexOutOfBounds exception.
Every time you remove an object from the bag, it shrinks in size (that is, neighbors.numObjs decreases by one). You test for this in the first example; but in the second, you've already loaded the very first numObjs into num and continue using that same number.