下面是迭代器和for循环的场景:
1)使用迭代器:
ihm.put("Zara", new Double(3434.34));
ihm.put("Mahnaz", new Double(123.22));
ihm.put("Ayan", new Double(1378.00));
ihm.put("Daisy", new Double(99.22));
ihm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = ihm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
========================================
使用 For 循环:
HashMap<String, Integer> map = new HashMap<String, Integer>();
//Adding key-value pairs
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
//Adds key-value pair 'ONE-111' only if it is not present in map
map.putIfAbsent("ONE", 111);
//Adds key-value pair 'FIVE-5' only if it is not present in map
map.putIfAbsent("FIVE", 5);
//Printing key-value pairs of map
Set<Entry<String, Integer>> entrySet = map.entrySet();
for (Entry<String, Integer> entry : entrySet)
{
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
在上面的两种情况下,迭代器和 for 循环都在做同样的工作。那么谁能告诉我它们之间有什么区别以及何时可以使用迭代器和 for 循环。
最佳答案
循环和迭代器之间的唯一显着区别(除了可读性之外)是,在使用迭代器时,您可以通过该迭代器实例编辑集合的内容。
如果您在循环遍历 map 时尝试编辑 map ,您将收到 Concurrent ModificationException
当您想在迭代 map 时更新 map 时,应该使用迭代器,例如删除符合某些条件的条目。
Iterator<Entry> it = map.iterator();
while(it.hasNext())
if(check(it.next()))
it.remove();
我必须注意,for-loop 是迭代器的语法糖,在生成的字节码中它们看起来是相同的。
关于java - hashmap中迭代器和for循环的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992063/