Reputation: 54113
I have this code:
for(int i = 0; i < oldCars.size(); ++i)
{
if(oldCars.get(i).getVelocity().length() > 0.0f)
{
oldCars.get(i).update(timeStep);
}
else
{
oldCars.remove(i);
}
}
It seems to work fine, but will it work in all conditions?
Thanks
Upvotes: 1
Views: 173
Reputation: 1451
You can use your method, but modify it slightly. When you remove an item from the list, the next item will get jumped over, so you will have to decrement i
each time you remove an item. So, you would have the following:
for(int i = 0; i < oldCars.size(); ++i)
{
if(oldCars.get(i).getVelocity().length() > 0.0f)
{
oldCars.get(i).update(timeStep);
}
else
{
oldCars.remove(i--);
}
}
Upvotes: 1
Reputation: 6075
Iterator<T> it = oldCars.iterator();
while (it.hasNext()) {
T oldCar = it.next();
if (oldCar.getVelocity().length() > 0.0f) {
oldCar.update(timeStep);
} else {
it.remove();
}
}
Upvotes: 2
Reputation: 8771
If you want to remove when iterating, start from the end :
for(int i = oldCars.size() - 1; i >= 0; i--)
{
if(oldCars.get(i).getVelocity().length() > 0.0f)
{
oldCars.get(i).update(timeStep);
}
else
{
oldCars.remove(i);
}
}
Upvotes: 10
Reputation: 12538
I guess it won't update all entries.
If you remove an entry your i
index goes up, however the next item would have the current i
value as well.
oldcar 1
oldcar 2
oldcar 3
Remove "oldcar 1" i will be 1 and the next entry you check is "oldcar 3" instead of "oldcar 2".
Upvotes: 3