简体   繁体   中英

Infinite loop using an iterator

I am new to Iterators and not sure what I'm doing wrong. In my project, Stations have Cars which have Passengers and Cars can also have Passengers. My goal is to check whether a Car has reached its target Station and, if it has not, move it along to the next one by removing it from the current station and adding it to the next one.

        Iterator<Station> stations = allStations.iterator();
        while(stations.hasNext())
        {
            Station currentStation = (Station)stations.next();
            ArrayList<Car> currentStationCars = currentStation.getCarList();
            Iterator cars = currentStationCars.iterator();
            Car currentCar = (Car)cars.next();
            while(cars.hasNext())
            {

Initially, I had currentCar declared here, but that was causing a NoSuchElement exception--I guess because I kept moving the cursor forward at every iteration. Not sure, I only just learned about this an hour ago. Now, this bit of code results in an infinite loop.

                //original position of currentCar declaration
                int stepper = 0;
                if(currentCar.getCurrentLocation() < currentCar.getDestination())
                {
                    stepper = 1;
                }
                else if(currentCar.getCurrentLocation() > currentCar.getDestination())
                {
                    stepper = -1;
                }
                while(stepper != 0)
                {
                    currentCar.setCurrentLocation(currentCar.getCurrentLocation() + stepper);
                    currentStation.removeCar(currentCar);
                    if(currentCar.getCurrentLocation() < currentCar.getDestination())
                    {
                        stepper = 1;
                    }
                    else if(currentCar.getCurrentLocation() > currentCar.getDestination())
                    {
                        stepper = -1;                       
                    }
                    else { 
                        stepper = 0; 
                    }
            }
        }

You are only advancing the iterator once, before the loop. This means that you'll get an exception if the list is empty (since you call cars.next() before checking that cars.hasNext() ), and an infinite loop if it has at least one element, since you don't advance to the next Car inside the loop.

You should only advance the iterator inside the loop:

while (cars.hasNext())
{
    Car currentCar = (Car)cars.next();
    ....
}

Note that you can avoid the casting if you used generic types:

Iterator<Car> cars = currentStationCars.iterator();
...
while(cars.hasNext())
{
    Car currentCar = cars.next();
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM