For-Each循环

•For-Each循环的加入简化了集合的遍历

•其語法如下

–for(type element : array) { System.out.println(element).... }

•参见程序 ForTest.java

当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式来实现循环或遍历,而不要使用增强的for循环,因为它丢失了下标信息。

 

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 import java.util.List;
 5 
 6 public class ForTest
 7 {
 8     public static void main(String[] args)
 9     {
10         int[] arr = { 1, 2, 3, 4, 5 };
11 
12         // 旧式方式
13         for (int i = 0; i < arr.length; i++)
14         {
15             System.out.println(arr[i]);
16         }
17 
18         System.out.println("--------------------------");
19 
20         // 新式方式,增强的for循环
21 
22         for (int element : arr)
23         {
24             System.out.println(element);
25         }
26 
27         System.out.println("--------------------------");
28 
29         String[] names = { "hello", "world", "welcome" };
30 
31         for (String name : names)
32         {
33             System.out.println(name);
34         }
35 
36         System.out.println("--------------------------");
37 
38         int[][] arr2 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
39         
40         for(int[] row : arr2)
41         {
42             for(int element : row)
43             {
44                 System.out.println(element);
45             }
46         }
47         
48         System.out.println("--------------------------");
49         
50         Collection<String> col = new ArrayList<String>();
51         
52         col.add("one");
53         col.add("two");
54         col.add("three");
55         
56         for(String str : col)
57         {
58             System.out.println(str);
59         }
60         
61         System.out.println("--------------------------");
62         
63         List<String> list = new ArrayList<String>();
64         
65         list.add("a");
66         list.add("b");
67         list.add("c");
68         
69         for(int i = 0; i < list.size(); i++)
70         {
71             System.out.println(list.get(i));
72         }
73         
74         System.out.println("--------------------------");
75         
76         for(Iterator<String> iter = list.iterator(); iter.hasNext();)
77         {
78             System.out.println(iter.next());
79         }
80         
81         System.out.println("--------------------------");
82         
83         for(String str : list)
84         {
85             System.out.println(str);
86         }
87     }
88 }

 

posted @ 2015-05-14 23:37  淡纷飞菊  阅读(290)  评论(0编辑  收藏  举报