遍歷列表的三種方法

JDK1.5之後,遍歷列表操作至少有三種方法:ForEach操作,迭代器和for循環。

使用方法如下:

String[] strs = new String[]{"1", "2", "3"};
List<String> list = Arrays.asList(strs);
for (String s: list) {//ForEach操作
    System.out.println(s);
}

for (Iterator it = list.iterator(); it.hasNext();) {//迭代器
    System.out.println(it.next());
}

for (int i=0; i<list.size(); i++) {//for循環
    System.out.println(list.get(i));
}

這三種遍歷操作效率對比如下:

對於ArrayList:

for循環 > 迭代器 > ForEach操作

對於LinkedList:

迭代器 > ForEach操作,不要使用for循環!

ForEach操作效率小於迭代器的原因是,ForEach循環會被解析成下面的代碼:

for (Iterator it = list.iterator(); it.hasNext();) {
    String s = (String) it.next();
    String s1 = s;//多餘的賦值
}

而迭代器遍歷被解析爲:

String s2;
for (Iterator it = list.iterator(); it.hasNext();) {
    s2 = (String) it.next();
}

ForEach循環中存在一步多餘的賦值操作。

發佈了15 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章