增强for循环的使用

增强for循环可以在数组和实现Iterable接口的Collection容器类中使用(需要注意的是,增强for循环只能遍历数据,不能修改数据),下面给出两个例子

1.在数组中的使用

1     @Test
2     public void demo(){
3         int[] a = {1,2,3,4,5};
4         for(int i : a){
5             System.out.print(i+" ");
6         }
7     }

输出为1,2,3,4,5

2.在实现Iterable接口的Collection容器类中使用

 1     @Test
 2     public void demo2(){
 3         List l = new LinkedList();
 4         l.add(1);
 5         l.add(2);
 6         l.add(3);
 7         l.add(4);
 8         l.add(5);
 9         for(Object obj : l){
10             int s = (Integer)obj;
11             System.out.print(s + " ");
12         }
13         
14     }

输出为1,2,3,4,5

 

原文地址:https://www.cnblogs.com/Vamps0911/p/10766197.html