Question

I'm trying to write a method that will return an ArrayList of Strings from my HashMap.

Currently I have a HashMap that contains a String as the identifier (key?), and a List of type String that holds all the values associated with it. The program is meant to mimic a train/subway navigation tool, so the first String is the station name, and the arraylist is a series of Strings showing all the connected stations.

Here is what I have so far, but it won't currently compile. There are several other methods which I know are working, so I've just put the final one which I'm having difficulty with (getConnections).

I'm very much a novice at this, so if someone could point out where I've gone wrong I'd really appreciate it.

public class MyNetwork implements Network {
    Map<String, List<String>> stations = new HashMap<>();

    @Override
    public String[] getConnections(String fromStation) {

    /**
     * Get a list of all stations directly connected to a given station.
     *
     * @pre fromStation has been added to the network by the method
     * addStation.
     * @param fromStation
     * @return A list of all the stations to which there is a direct
     * connection from fromStation.
     */
    ArrayList<String> Connections = new ArrayList<>();
    Set<String> keys = stations.keySet();

    for (String k : keys) {
        String keyValue;
        keyValue = (stations.get(fromStation));
    }

    return fromStation;
}
Was it helpful?

Solution

There's no need to explicitly iterate over the values in the Map, just use built-in methods. The whole getConnections() implementation can be written in a single line:

return stations.get(fromStation).toArray(new String[0]);

How it works:

  • First we obtain the list of connections for a given station, using get()
  • The previous step returns a List<String>
  • Now we only need to convert it to a String[] using toArray(). For type safety we pass an array of the expected return type

Alternatively, you could also change the return type to List<String>, unless strictly necessary there's no need to convert a List to an array; if you decide to do this the toArray() call would be unnecessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top