簡體   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