簡體   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