繁体   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