Reputation: 67
I'm having a little difficulty getting my head around a hashmap I'm trying to implement. The basic premise is that I have a list of stations in a txt file, with the "connections" between each. Something like;
Connection: Station1 Station2
Connection: Station4 Station6
I have several methods, which will add a station name as a string, and then store its "connected" stations in an arraylist which I can then later retrieve to show "Station4: Connected to Station 6" and so on.
The two methods below i'm concerned with are the "add stations" and the "add connection" ones I've set it up so the Hashmap "stations" should contain a String > Arraylist relationship. My thinking was that the "String" would store the station name, and then the arraylist "connectedstations" would store all the stations that it's connected to, I just don't know how to create the association? I've written some before using a Key, but I can't seem to get anything to work here!
Any help would be really appreciated! Thanks
public class MyNetwork implements Network {
//The Hashmap of type String, Arraylist. The String holding the
//station name, and the arraylist holding the stations connected to it
HashMap<String, ArrayList> stations = new HashMap<>();
//the arraylist to hold the connected stations
ArrayList<String> connectedstations = new ArrayList<>();
@Override
public void addStation(String station) {
//adds a station to the hashmap, pointing to a CURRENTLY empty
//arraylist "connectedstations"
stations.put(station,connectedstations);
}
@Override
public void addConnection(String fromStation, String toStation) {
/**
* Add a direct connection from one station to another.
* @pre both fromStation and toStation have already been added by the method
* addStation.
* @param fromStation The station from which the connection begins.
* @param toStation The station at which the connection ends.
*/
}
Upvotes: 0
Views: 2390
Reputation: 691625
Your current code adds the same list of connections for all the stations added to the map. That can't be right, since every station has its own list of connections.
addStation()
should add a station to the map, with a new empty list as value.
addConnection()
should get the list of connections associated to the station in the map, and should add a station to this list.
Just a few additional notes:
Map<String, List<String>>
Upvotes: 2