繁体   English   中英

使用迭代器的无限循环

[英]Infinite loop using an iterator

我是Iterators的新手,不确定自己在做什么错。 在我的项目中,车站有载客的汽车,而汽车也有载客。 我的目标是检查汽车是否已到达目标站点,如果尚未到达,请通过将其从当前站点移除并将其添加到下一个站点来将其移动到下一个站点。

        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())
            {

最初,我在这里声明了currentCar,但是这导致了NoSuchElement异常-我猜是因为我每次迭代都不断向前移动光标。 不确定,我只是一个小时前才了解到这一点。 现在,这段代码会导致无限循环。

                //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; 
                    }
            }
        }

在循环之前,您只需将迭代器前进一次。 这意味着,即使你的列表是空的得到一个异常(因为你调用cars.next()检查之前cars.hasNext()如果有至少一个元素,因为你没有一个无限循环前进到循环内的下一Car

您只应在循环内推进迭代器:

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

请注意,如果使用泛型类型,则可以避免强制转换:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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