從JDK1.5起,增加了新功能Foreach,它是for循環(huán)遍歷數(shù)據(jù)的一種簡寫形式,使用的關(guān)鍵字依然是for,但參數(shù)格式不同。其詳細用法為:
1
2
|
for (Type e:collection){ //對變量e的使用} |
參數(shù)說明:
e:其類型Type是集合或數(shù)組中元素值的類型,該參數(shù)是集合或數(shù)組collection中的一個元素。
collections: 要遍歷的集合或數(shù)組,也可以是迭代器。
在循環(huán)體中使用參數(shù)e,該參數(shù)是foreach從集合或數(shù)組以及迭代器中取得的元素值,元素值是從頭到尾進行遍歷的。
具體例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
//必須導(dǎo)入util下面的這兩個包:ArrayList,List; import java.util.ArrayList; import java.util.List; public class Foreach { public static void main(String[] arg){ List<String> list = new ArrayList<String>(); //創(chuàng)建List集合 list.add( "abc" ); //初始化list集合 list.add( "def" ); list.add( "ghi" ); list.add( "jkl" ); list.add( "mno" ); list.add( "pqr" ); System.out.print( "Foreach遍歷集合: \n\t" ); for (String string:list){ //遍歷List集合 System.out.print(string); //輸出集合的元素值 } System.out.println(); String[] strs = new String[list.size()]; list.toArray(strs); //創(chuàng)建數(shù)組 System.out.println( "Foreach遍歷數(shù)組:\n\t" ); for (String string: strs){ //遍歷數(shù)組 System.out.print(string); //輸出數(shù)組元素值 } } } |
總結(jié):
JDK之前的版本使用for循環(huán)對集合、數(shù)組和迭代器進行遍歷,這需要創(chuàng)建索引變量、條件表達式,這些會造成代碼混亂,并增加出錯的幾率。并且每次循環(huán)中,索引變量或迭代器都會出現(xiàn)3次,有兩次出錯的機會。并且會有一些性能方面的損失、其性能稍微落后于foreach循環(huán)。所以對于數(shù)據(jù)集合的遍歷,建議使用Foreach循環(huán)。