有沒有辦法從一個特定的鍵開始在HashMap中迭代?如何從Java中的特定鍵值開始遍歷HashMap?
假設我的地圖是:
Map map = new HashMap();
map.put(1,"A");
map.put(2,"B");
map.put(3,"B");
map.put(4,"B");
map.put(5,"F");
map.put(6,"Z");
而且我要重複,將來自主要2
開始。
常規迭代包括:
public static void printMap(Map map) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
但是如何從一個特定的鍵啓動迭代?
由於迭代順序未定義,您無法使用HashMap執行此操作。你想要一個TreeMap(或者查看你的索引,也許只是一個數組或列表)。 – Thilo
另外,在你的例子中,你將'map'定義爲[原始類型](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-用它)。最好不要這樣做(見鏈接)。嘗試使用Map map = new HashMap ()'。 :) –
Gulllie
您是否使用地圖上的鍵(1,2,3,...)作爲某種索引?還是僅僅爲了這個例子? – smsnheck