For Each Loop vs. Iterator: Efficiency in Collection Traversal
Introduction
When traversing a collection in Java, the choice arises between using a for-each loop and an iterator.本文探討了這兩種方法之間的效率差異。
for-east loop 在Java 5中介紹的,for-east loop(也稱為loop的增強型)是一個簡潔的和易於閱讀的概述,並且易於讀取概述的概述。它在內部使用迭代器: list
迭代器提供了一個標準化的接口,用於迭代集合。它允許對遍歷過程進行自定義控制。
listList很少,請訪問量很大, for-each內部使用迭代器機制。a = new ArrayList(); for (Integer integer : a) { integer.toString(); }
,但是,如果使用傳統的“ c-style”循環(i):迭代器方法(均可進行循環和顯式迭代器)對於某些數據結構而言,效率更高。例如,在鏈接列表中,get(i)是O(n)操作。 Using an iterator's O(1) next() operation ensures the loop runs in O(n) time, whereas the get(i) loop would run in O(n2
) time.Lista = new ArrayList(); for (Iterator iterator = a.iterator(); iterator.hasNext();) { Integer integer = iterator.next(); integer.toString(); }
To confirm that the for-each loop uses the iterator mechanism, we can compare the generated這兩種方法的字節碼:
aload 1 InvokeInterface Java/util/list.iterator()ljava/util/iterator; 阿斯托爾3 ...list
aload 1 InvokeInterface Java/util/list.iterator()ljava/util/iterator; ASTORE 2 ...
for (int i = 0; i [&&&&&&&&&&&&&&&&&&&&&&&&&&&& && && && && && &&&&& ussary在摘要中訪問唯一的訪問集合時,在讀取的集合中,是一個for-each for-each iSain isain和each isain isain isain and atar anstain and ataer and ataer andar inator anstar ander inator inator andor andor anstar ander inator。迭代器僅在使用特定數據結構或需要自定義迭代行為時提供優勢。為了簡單性和可讀性,for-EAPE循環通常是首選的選擇。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3