某人問我增強for循環是什么,其實我只是會用,所以上網查了一下,如下:
For-Each循環
For-Each循環也叫增強型的for循環,或者叫foreach循環。
For-Each循環是JDK5.0的新特性(其他新特性比如泛型、自動裝箱等)。
For-Each循環的加入簡化了集合的遍歷。
其語法如下:
for(type 變量名: array)
{
System.out.println(變量名);
}
例子
其基本使用可以直接看代碼:
代碼中首先對比了兩種for循環;之后實現了用增強for循環遍歷二維數組;最后采用三種方式遍歷了一個List集合。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ForeachTest
{
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5};
System.out.println("----------舊方式遍歷------------");
//舊式方式
for(int i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
System.out.println("---------新方式遍歷-------------");
//新式寫法,增強的for循環
for(int element:arr)
{
System.out.println(element);
}
System.out.println("---------遍歷二維數組-------------");
//遍歷二維數組
int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ;
for(int[] row : arr2)
{
for(int element : row)
{
System.out.println(element);
}
}
//以三種方式遍歷集合List
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
System.out.println("----------方式1-----------");
//第一種方式,普通for循環
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
System.out.println("----------方式2-----------");
//第二種方式,使用迭代器
for(Iterator<String> iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
System.out.println("----------方式3-----------");
//第三種方式,使用增強型的for循環
for(String str: list)
{
System.out.println(str);
}
}
}
任何新特性有利就一定會有一些弊端,增強for循環在簡潔的同時也是有缺點的:
1.當遍歷集合或數組時,如果需要訪問集合或數組的下標,那么最好使用舊式的方式來實現循環或遍歷,而不要使用增強的for循環,因為它丟失了下標信息。
2.增強for循環和iterator遍歷的效果是一樣的,也就說 增強for循環的內部也就是調用iteratoer實現的,但是增強for循環 有些缺點,例如不能在增強循環里動態的刪除集合內容。不能獲取下標等。
本文引用自:http://www.cnblogs.com/mengdd/archive/2013/01/21/2870019.html

