繁体   English   中英

JAVA:HashMap <String, ArrayList> - 我如何关联这些值?

[英]JAVA: HashMap<String, ArrayList> - How can I associate the values?

我正在努力解决我正在尝试实现的哈希映射问题。 基本前提是我在txt文件中有一个站列表,每个站点之间有“连接”。 就像是;

连接:Station1 Station2

连接:Station4 Station6

我有几种方法,它们将一个站名添加为一个字符串,然后将它的“连接”站存储在一个arraylist中,然后我可以检索它以显示“Station4:Connected to Station 6”,依此类推。

下面我关注的两个方法是“添加站”和“添加连接”我设置的方法,因此Hashmap“站点”应该包含一个String> Arraylist关系。 我的想法是“字符串”将存储电台名称,然后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.
 */


}

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

addStation()应该将一个工作站添加到地图中,并将新的空列表作为值。

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

只需补充几点说明:

  • Map的类型应该是Map<String, List<String>>
  • 您可以使用具有Multimaps的Guava,使这个过程更容易:无需关心初始化空列表,能够直接添加到多图,而不是从列表中获取列表并添加到列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM