1

I'm at the end of writing some code that will manage a 'dummy' train/subway network of stations. I have implemented it using a Map of type Map (String), (List)(String). The final method (the one I'm now struggling with) Should return all the 'stations' that have been added to the network, without duplicates. I'm trying to just get the values to return at the moment, however any advice on both issues would be appreciated. I've included below how I've set up the map, and the method in question. Ideally i'd like these values to be returned as an array, but the compiler seems to be taking some issue with my syntax. Thanks again!

public class MyNetwork implements Network {

Map<String, List<String>> stations = new HashMap<>();

@Override
public String[] getStations() {
 /**
 * Get all stations in the network.
 * @return An array containing all the stations in the network, with no
 * duplicates.
 */

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

}

3 Answers 3

4

See the keySet() method of maps, and to go further, see the toArray() method of sets.

A small code sample would look something like this:

public String[] getStations() {
        /* the reason you need to give the new String array to the toArray() method is, 
        so that the compiler knows that it is in fact an array of String, not just plain array of object */
        return stations.keySet().toArray(new String[0]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Zavior, managed to get there in the end! Just still wrapping my head round the syntax, its all rather tricky at the beginning!
1

see map.keySet().toArray() if you need array of elements.

Comments

1

Look at the Map API: Map#keySet() (http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#keySet()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.