2013-03-18 68 views
1

我在更新一些舊的Java代碼,我還沒有在一段時間接觸的過程中,有關於下面的代碼片段一個簡單的問題:爪哇 - 經歷一個哈希表

private Map<String, Example> examples = new ConcurrentHashMap<String, Example>(); 

...

public void testMethod() { 
    Enumeration allExamples = examples.elements(); 
    while (allExamples.hasMoreElements()){ 
    //get the next example 
    Example eg = (Example) allExamples.nextElement(); 
    eg.doSomething(); 

}

它以前使用的哈希表,但是我更換了一個線程安全的哈希表。 我的問題是,通過hashmap迭代的最佳方式是什麼?因爲枚舉已被棄用。我應該爲每個循環使用一個嗎?

任何意見將不勝感激。

+0

每一個是正確的答案。但是如果你想要更多的東西,你可以使用Iterator。 – 2013-03-18 15:24:06

+0

'HashMap#keySet()。iterator();'是你正在尋找的。 – 2013-03-18 15:24:11

+0

還有http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap – NPE 2013-03-18 15:25:35

回答

4

只是使用一個for-each loop,for-each /增強環是爲了iterating的目的而引入的一個集合/數組。但是,只有當您的集合實現了接口時,您才能使用for-each迭代集合。

for(Map.Entry<String, Example> en: example.entrySet()){ 
System.out.println(en.getKey() + " " + en.getValue()); 
} 
0

既然你只處理值:

public void testMethod() 
{ 
    for (Example ex : allExamples.values()) 
    { 
     ex.doSomething(); 
    } 
}