2012-11-01 43 views
0

我有一個自定義Map,其中Device是我的類的一個實例,名爲Device。Java如何迭代Map <String,Device>

devices = new HashMap<String, Device>(); 

我試了幾個迭代和循環在StackOverflow的建議,但他們都似乎產生錯誤,我不知道爲什麼。

實例錯誤:

enter image description here

enter image description here

+2

您遇到的錯誤是什麼?以及張貼您嘗試過的代碼也可能有幫助。 – kosa

+0

這裏有一個方法,對我有用:http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap – Graknol

+0

我添加了錯誤的屏幕截圖 – xorinzor

回答

3

貌似的devices的聲明是不正確。它應該是:

Map<String, Device> devices; 

不是原始(「擦除」)類型Map。現代編譯器應該給你使用原始類型的警告。記下編譯器警告。

+0

這個伎倆,謝謝! – xorinzor

0

你可以試試這個:

HashMap<String, Device> devices = new HashMap<String, Device>(); 

// do stuff to load devices 

Device currentDevice; 
for (String key : devices.keySet()) { 

    currentDevice = devices.get(key); 
    // do stuff with current device 

} 
+0

這是在跟蹤密鑰的同時迭代哈希映射的最簡潔的方式。 – Jiman

0

在第一種情況下,你只要給

爲(Map.Entry的條目:devices.entrySet()){}

只有足夠的,你不需要投的Map.Entry(字符串,設備)。在第二種情況下,當你從項的值,它返回對象的值,所以你需要投放到特定instance.So你必須給

設備裝置=(設備)pairs.getValue()

0

有3種方法可以在地圖上迭代 1)使用For-Each循環遍歷條目。 2)使用For-Each循環遍歷鍵或值。 3)使用Iterator迭代。 (爲此,您可以迭代使用泛型或不使用泛型)

Map map = new HashMap(); 
Iterator entries = map.entrySet().iterator(); 
while (entries.hasNext()) { 
    Map.Entry entry = (Map.Entry) entries.next(); 
    Integer key = (Integer)entry.getKey(); 
    Integer value = (Integer)entry.getValue(); 
    System.out.println("Key = " + key + ", Value = " + value); 
} 
相關問題