jmasterx
jmasterx

Reputation: 54113

Can I remove from a list while iterating it?

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

Answers (4)

Wesley Porter
Wesley Porter

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

Liviu Stirb
Liviu Stirb

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

Alexandre Lavoie
Alexandre Lavoie

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

Udo Held
Udo Held

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

Related Questions