整體來說:
增強(qiáng)型for循環(huán)使用起來比較方便,代碼也比較簡單,如果只是操作集合中元素的而不使用索引的話,建議用此方法。
對(duì)于普通for循環(huán),如果需要使用索引進(jìn)行其它操作的話,建議用這個(gè)。
詳細(xì)來說:
1,區(qū)別:
增強(qiáng)for循環(huán)必須有被遍歷的目標(biāo)(如集合或數(shù)組)。
普通for循環(huán)遍歷數(shù)組的時(shí)候需要索引。
增強(qiáng)for循環(huán)不能獲取下標(biāo),所以遍歷數(shù)組時(shí)最好使用普通for循環(huán)。
2,特點(diǎn):
書寫簡潔。
對(duì)集合進(jìn)行遍歷,只能獲取集合元素,不能對(duì)集合進(jìn)行操作,類似迭代器的簡寫形式,但是迭代器可以對(duì)元素進(jìn)行remove操作(ListIterator可以進(jìn)行增刪改查的操作)。
3,格式:
for(數(shù)據(jù)類型變量名 :被遍歷的集合(collection)或者數(shù)組) {
執(zhí)行語句
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ForTest {
? ? ? ? public static void main(String[] args) {
? ? ? ? ? ? ? ? // TODO Auto-generated method stub
? ? ? ? ? ? ? ? /* 1.普通數(shù)組中的使用 */?
? ? ? ? int array[] = { 1,2,3,4,5,6,7,8,9};?
? ? ? ? // 增強(qiáng)for循環(huán)?
? ? ? ? for (int item : array) {?
? ? ? ? ? ? System.out.println(item);?
? ? ? ? }?
? ? ? ? // 普通for循環(huán)
? ? ? ? for (int i = 0; i < array.length; i++)?
? ? ? ? ? ? System.out.println(array[i]);?
? ? ? ? /* 2.二維數(shù)組中的使用 */?
? ? ? ? int array2[][] = {{1,2,3}, {4,5,6}, {7,8,9} };?
? ? ? ? // 增強(qiáng)for循環(huán)?
? ? ? ? for (int arr[] : array2) {?
? ? ? ? ? ? for (int item : arr) {?
? ? ? ? ? ? ? ? System.out.println(item);?
? ? ? ? ? ? }?
? ? ? ? }?
? ? ? ? // 普通for循環(huán)?
? ? ? ? for (int i = 0; i < array2.length; i++) {?
? ? ? ? ? ? for (int j = 0; j < array2[i].length; j++) {?
? ? ? ? ? ? ? ? System.out.println(array2[i][j]);?
? ? ? ? ? ? }?
? ? ? ? }?
? ? ? ? /* 3.List中的使用 */?
? ? ? ? List<String> list = new ArrayList<String>();?
? ? ? ? list.add("我");?
? ? ? ? list.add("愛");?
? ? ? ? list.add("中");?
? ? ? ? list.add("國");
? ? ? ? // 增強(qiáng)for循環(huán)?
? ? ? ? for (String item : list){?
? ? ? ? ? ? System.out.println(item);? ? ? ? ? ?
? ? ? ? }?
? ? ? ? //普通for循環(huán)
? ? ? ? for (int i = 0; i < list.size(); i++) {?
? ? ? ? ? ? System.out.println(list.get(i));?
? ? ? ? }?
? ? ? ? //迭代器遍歷?
? ? ? ? Iterator<String> it = list.iterator();
? ? ? ? while (it.hasNext()) {?
? ? ? ? ? ? System.out.println(it.next());?
? ? ? ? }?
? ? ? ? }
}