- Java 5.0 提供了 foreach 循环迭代访问 Collection和数组。
- 遍历操作不需获取Collection或数组的长度,无需使用索引访问元素。
- 遍历集合的底层调用Iterator完成操作。
- foreach还可以用来遍历数组。
1 @Test
2 public void test(){
3 Collection coll = new ArrayList();
4 coll.add(123);
5 coll.add(456);
6 coll.add("B");
7 coll.add(false);
8 //for(集合元素的类型 局部变量 集合对象)
9 //内部调用了迭代器
10 for(Object obj :coll){
11 System.out.println(obj);
12 }
13 }
14 @Test
15 public void test1(){
16 int[] arr=new int[]{1,3,3,5,6,6,7};
17 //for(数组元素的类型 局部变量 数组对象)
18 for(int i: arr){
19 System.out.println(i);
20 }
21 }