增强for循环底层依然是迭代器。 因为单步调试,我们是可以进来的。
增强for也是我们在开发中使用最多的一种遍历方式。
可以实现各种数据类型的遍历。
package org.example.testFor;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// 遍历Set
Set<Integer> set = Sets.newHashSet(1, 2, 5, 4, 3);
for (Integer num : set) {
System.out.println(num);
}
// 遍历HashMap
Map<Integer, String> map = Maps.newHashMap();
map.put(1, "123");
map.put(2, "456");
for (Integer key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
}
}
/*
1
2
3
4
5
1:123
2:456
*/