簡體   English   中英

為每個循環嵌套?

[英]Nested for each loops?

        for ( Route r : timetable.keySet())
        {
            for (Station s: r?)   //compile error here.
        }

大家好,基本上,我正在嘗試編寫一種將時間表中的站點添加到組合框的方法。 時間表本質上是一個返回路線,列表(服務類型)的哈希表,並且路線由表示路線名稱的字符串定義,並且

// a list of stations visited on this route 
private ArrayList<Station> stations;

基本上,我需要訪問路線中的站點,因此我使用了一個foreach循環來獲取時間表中的每個路徑,然后嘗試獲取該路徑中的所有站點,但是我不確定如何進行第二個嵌套循環,當我引用路由時遇到編譯錯誤,因此我應該參考哪個列表。

我無法修改Route類,因為已經提供了該類,因此我需要解決此問題,但是它確實具有返回站的方法

   public Station getStop(int i) {
    if (i < 1 || i > stations.size()) {
        throw new NoSuchStopException("No " + i + "th stop on route" + this);
    }
    return stations.get(i - 1);
}

您將必須修改Route類並添加一個返回ArrayListgetter方法(因為它是private ):

public class Route {
    // ...

    public List<Station> getStations()
    {
        return stations;
    }
}

然后,您可以在for循環中使用該方法:

for (Route r : timetable.keySet()) {
    for (Station s : r.getStations()) {
        // ...
    }   
}

編輯:如@DavidWallace所述,如果您不希望有人通過getter方法修改ArrayList ,則可以返回一個unmodifiableList

return Collections.unmodifiableList(stations);

您可以實現以下解決方案,但是它不使用嵌套的for-each循環,因為它需要捕獲異常以知道何時該路由沒有更多的站(此解決方案不需要對Route類進行任何更改):

for ( Route r : timetable.keySet())
{
    int stationIndex = 1;
    try {
        do {
            Station station = route.getStop(stationIndex++);
            // todo - put the station in the combo box
        } while(true);
    } catch(NoSuchStopException nsse) {
        // we have reached the index where there wasn't a stop, so move to the next route
    }
}

你可以這樣寫

for ( Route r : timetable.keySet()) {
    for (Station s: r.getStations()) {

        // ...

    }
}

如果Route類具有類似

public List<Station> getStations() {
    return Collections.unmodifiableList(stations);
}

注意使用unmodifiableList 這樣可以防止某人編寫調用getStations代碼,然后修改結果。 基本上,應該不可能使用“ getter”方法來修改類。 因此,對於返回集合的getter,在Collections類中使用各種“不可修改的”包裝器方法是最佳實踐。

編輯

處理不能更改Route的新要求,並假設存在方法getNumberOfStops和問題的getStop ,則可以編寫

for (Route r : timetable.keySet()) {
    for (int stopNumber = 1; stopNumber <= r.getNumberOfStops(); stopNumber++) {
        Station s = r.getStop(stopNumber);
        // ...
    }
}

for-each循環迭代集合或數組類型,而Route對象r不是可迭代的類型,這就是為什么它引發編譯器錯誤

for ( Route r : timetable.keySet()){
     for (Station s: r.getStations()){ // Get the station List from route object
       ...
     }   
}

注意:假設在Route類中必須有stations吸氣劑方法。

每個循環的說明

for(XXX a : YYY)    
YYY --- > should be any class that implements iterable  
and XXX objects should be in YYY 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM