我在更新一些旧的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迭代的最佳方式是什么?因为枚举已被弃用。我应该为每个循环使用一个吗?
任何意见将不胜感激。
每一个是正确的答案。但是如果你想要更多的东西,你可以使用Iterator。 – 2013-03-18 15:24:06
'HashMap#keySet()。iterator();'是你正在寻找的。 – 2013-03-18 15:24:11
还有http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap – NPE 2013-03-18 15:25:35