Reputation: 1114
I'm trying to loop over a array of brickEnemies and if my condition is true then the brick should be removed from my array. I get the following error IndexOutOfBoundsException. How could I make my for loop keep going after i have removed an element?
int lengthofBrickEnemies = brickEnemies.size();
for (int i = 0; i < lengthofBrickEnemies; i++) {
Brick brick = brickEnemies.get(i);
int newPosition_X = brick.getPositionX() - SPEED;
if (newPosition_X > 0) {
brick.setPositionX(newPosition_X);
} else {
brickEnemies.remove(i);
}
}
Upvotes: 0
Views: 113
Reputation: 14847
It's not an Array
, but an ArrayList
.
To remove an item from an ArrayList
while you are reading it you should use an Iterator
and then Iterator.remove()
method.
Will be:
Iterator<Brick> it = brickEnemies.iterator();
while (it.hasNext()) {
Brick brick = it.next();
int newPosition_X = brick.getPositionX() - SPEED;
if (newPosition_X > 0) {
brick.setPositionX(newPosition_X);
} else {
it.remove();
}
}
it.remove();
removes the item returned by .next()
call.
hasNext()
is used to make sure there are more items to iterate in the ArrayList
.
Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Upvotes: 4