Quiz: driveCars
The answer in the video is wrong. See if you can spot the error.
The problem is that there are two i++: in the for loop and in the else.
It is always dangerous to change the variable that is controlled by the for loop. A while loop is the safer choice:
int i = 0;
while (i < cars.size())
{
Car c = cars.get(i);
c.drive();
if (c.hasArrived())
{
cars.remove(i);
}
else
{
i++;
}
}
Alternatively, if you use a for loop and remove elements, traverse the list backwards:
for (int i = cars.size() - 1; i >= 0; i--)
{
Car c = cars.get(i);
c.drive();
if (c.hasArrived())
{
cars.remove(i);
}
}