I've been stuck on this question in an assignment in which I must "List the stations along a given subway line" There are two Hash Maps:
private Map<String, Station> allStations = new HashMap<String, Station>(); // all stations, indexed by station name
private Map<String, SubwayLine> allSubwayLines = new HashMap<String, SubwayLine>(); // all subway lines, indexed by name of the line
I am trying to call the "getStations()" method, which is a part of the subwayLine class:
public List<Station> getStations(){
return Collections.unmodifiableList(stations);
}
On a subwayLine object which is linked to a button:
public void listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
for(SubwayLine s : subwayLines){
s.getStations();
}
}
However, this does nothing. Is there anyway in which I can return the stations along the given subwayLine?
CodePudding user response:
you have to save your data in an arraylist again :
public void listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
List<Collection<Station>> stations = new ArrayList();
for(SubwayLine s : subwayLines){
stations.add(s.getStations());
}
}
CodePudding user response:
The void
keyword in your method means that it does not return anything.
You might want to replace it with List and return it at the end of your method, like
public List<Station> listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
List<Collection<Station>> stations = new ArrayList<>();
for(SubwayLine s : subwayLines){
stations.add(s.getStations());
}
return stations
}
Please note that you loop through all subwaylines and therefore your stations arraylist consists of all stations that are along some subwayline. So not a list of stations per subwayline. Also, I added a diamond operator to the arraylist call. That will automatically make an ArrayList of the type Collection<Station>
. However, making a List of Collections seems not right here? You probably just want a List of <Station>
.
Moreover, the call s.getStations()
seems to yield all stations at subwayLine s? The description of your question seems to ask how to implement thát method.
In your question, you seem to prefer a list of stations for a given subwayline. That should then be input for your method, something like this:
public List<Station> listStationsOnLine(SubwayLine subwayline){
UI.clearText();
List<Station> allStations = getStations();
List<Station> stations = new ArrayList<>();
for(Station s : allStations){
if(s.onLine(subwayline)) {
stations.add(s);
}
}
return stations
}