對於遍歷數組,這個循環一般是採取這樣的寫法:
清單1:遍歷數組的傳統方式
- /* 建立一個數組 */
- int[] integers = {1, 2, 3, 4};
- /* 開始遍歷 */
- for (int j = 0; j < integers.length; j++) {
- int i = integers[j];
- System.out.println(i);
- }
而對於遍歷Collection對象,這個循環則通常是採用這樣的寫法:
清單2:遍歷Collection對象的傳統方式
- /* 建立一個Collection */
- String[] strings = {"A", "B", "C", "D"};
- Collection stringList = java.util.Arrays.asList(strings);
- /* 開始遍歷 */
- for (Iterator itr = stringList.iterator(); itr.hasNext();) {
- Object str = itr.next();
- System.out.println(str);
- }
而在Java語言的最新版本——J2SE 1.5中,引入了另一種形式的for循環。藉助這種形式的for循環,現在可以用一種更簡單地方式來進行遍歷的工作。
第二種for循環
不嚴格的說,Java的第二種for循環基本是這樣的格式:
for (循環變量類型 循環變量名稱 : 要被遍歷的對象) 循環體
藉助這種語法,遍歷一個數組的操作就可以採取這樣的寫法:
清單3:遍歷數組的簡單方式
- /* 建立一個數組 */
- int[] integers = {1, 2, 3, 4};
- /* 開始遍歷 */
- for (int i : integers) {
- System.out.println(i);/* 依次輸出“1”、“2”、“3”、“4” */
- }
這裏所用的for循環,會在編譯期間被看成是這樣的形式:
清單4:遍歷數組的簡單方式的等價代碼
- /* 建立一個數組 */
- int[] integers = {1, 2, 3, 4};
- /* 開始遍歷 */
- for (int 變量名甲 = 0; 變量名甲 < integers.length; 變量名甲++) {
- System.out.println(變量名甲);/* 依次輸出“1”、“2”、“3”、“4” */
- }
這裏的“變量名甲”是一個由編譯器自動生成的不會造成混亂的名字。
而遍歷一個Collection的操作也就可以採用這樣的寫法:
清單5:遍歷Collection的簡單方式
- /* 建立一個Collection */
- String[] strings = {"A", "B", "C", "D"};
- Collection list = java.util.Arrays.asList(strings);
- /* 開始遍歷 */
- for (Object str : list) {
- System.out.println(str);/* 依次輸出“A”、“B”、“C”、“D” */
- }
這裏所用的for循環,則會在編譯期間被看成是這樣的形式:
清單6:遍歷Collection的簡單方式的等價代碼
- /* 建立一個Collection */
- String[] strings = {"A", "B", "C", "D"};
- Collection stringList = java.util.Arrays.asList(strings);
- /* 開始遍歷 */
- for (Iterator 變量名乙 = list.iterator(); 變量名乙.hasNext();) {
- System.out.println(變量名乙.next());/* 依次輸出“A”、“B”、“C”、“D” */
- }
這裏的“變量名乙”也是一個由編譯器自動生成的不會造成混亂的名字。
因爲在編譯期間,J2SE 1.5的編譯器會把這種形式的for循環,看成是對應的傳統形式,所以不必擔心出現性能方面的問題。