→阿童沐

財富==支撐一個人生存多長時間的能力!

导航

<JDK1.5新特性>:2.For-Each循环遍历集合类-

For-Each循环的加入简化了对集合数组的遍历

其语法如下:

for(Type element : List) {
System.out.println(element);
...
}

例如:

1.一维数组的遍历

package cn.edu.bupt.genericinterface;

public class ForTest {

/**
*
@param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1, 2, 3, 4, 5};

//普通for循环
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}

System.out.println("--------------------");

//增强for循环
for(int i : arr) {
System.out.println(i);
}
}

}

 

2.二维数组的增强for循环遍历

package cn.edu.bupt.genericinterface;

public class ForTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//二维数组的循环
int[][] a = new int[3][];
for(int i=0; i<3; i++) {
a[i] = new int[]{i, i+1, i+2};
}
for(int[] b : a) {
for(int c : b) {
System.out.print(c + ", ");
}
System.out.println();
}
}

}

 

3.集合类的遍历

package cn.edu.bupt.genericinterface;

import java.util.Collection;
import java.util.LinkedList;

public class ForTest {
public static void main(String[] args) {
Collection<String> col = new LinkedList<String>();
col.add("one");
col.add("two");
col.add("three");

for(String str : col) {
System.out.println(str);
}
}
}


说明:

    当遍历集合或数组的时候,如果需要访问集合或数组的下标(索引),那么最好使用旧的方式来实现

循环或遍历,而不要使用增强for循环,因为它丢失了下标信息; 




posted on 2012-01-31 20:18  阿童沐  阅读(207)  评论(0)    收藏  举报