2013-03-18 43 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(); 
    } 
}