下面只是简单介绍各种遍历示例(以HashMap为例),各自优劣会在本文后面进行分析给出结论。
(1) for each map.entrySet()
1
2
3
4
5
| Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
|
(2) 显示调用map.entrySet()的集合迭代器
1
2
3
4
5
6
| Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
entry.getKey();
entry.getValue();
}
|
(3) for each map.keySet(),再调用get获取
1
2
3
4
| Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
map.get(key);
}
|
(4) for each map.entrySet(),用临时变量保存map.entrySet()
1
2
3
4
5
| Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
entry.getKey();
entry.getValue();
}
|
在测试前大家可以根据对HashMap的了解,想想上面四种遍历方式哪个性能更优。