0

我很难理解我正在尝试实现的哈希图。基本前提是我在 txt 文件中有一个站点列表,每个站点之间都有“连接”。就像是;

连接:Station1 Station2

连接:Station4 Station6

我有几种方法,它们会将站点名称添加为字符串,然后将其“已连接”站点存储在一个数组列表中,然后我可以稍后检索它以显示“Station4:已连接到站点 6”等等。

下面我关心的两种方法是我设置的“添加站”和“添加连接”,因此 Hashmap“站”应该包含 String > Arraylist 关系。我的想法是“字符串”将存储电台名称,然后数组列表“connectedstations”将存储它连接到的所有电台,我只是不知道如何创建关联?我在使用 Key 之前写了一些,但我似乎无法在这里工作!

任何帮助将非常感激!谢谢

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.
 */


}
4

1 回答 1

2

您当前的代码为添加到地图的所有站点添加了相同的连接列表。这是不对的,因为每个站点都有自己的连接列表。

addStation()应该在地图上添加一个站点,并以一个新的空列表作为值。

addConnection()应该获取与地图中的车站相关联的连接列表,并应将车站添加到此列表中。

只是一些额外的说明:

  • 地图的类型应该是Map<String, List<String>>
  • 您可以使用具有 Multimaps 的 Guava,使此过程更容易:无需关心初始化空列表,能够直接添加到 multimap,而不是从列表中取出列表并添加到列表中。
于 2014-02-14T16:33:42.900 回答