2014-02-16 74 views
1

我在寫一些代碼,將管理一個'虛擬'火車/地鐵站的網絡結束。我已經使用Map(String),(List)(String)類型的Map來實現它。最後的方法(我現在正在努力的方法)應該返回已添加到網絡中的所有「工作站」,而不是重複的。我正努力讓這些價值能夠在目前得到回報,但是對這兩個問題的任何建議都將不勝感激。我在下面介紹了我如何設置地圖,以及所討論的方法。理想情況下,我希望這些值以數組的形式返回,但編譯器似乎在處理我的語法時遇到了一些問題。再次感謝!JAVA:返回所有關鍵值從Hashmap

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]); 

} 

回答

4

見地圖的keySet()方法,並進一步去,看到的套toArray()方法。

一個小的代碼示例會是這個樣子:

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]); 
} 
+0

謝謝Zavior,設法到最後!只是仍然把我的頭放在句法上,它的一開始就相當棘手! – JavaStarta

1

看到map.keySet()指定者(),如果你需要的元素的數組。