Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming this is what you meant:</p> <pre><code>// traditional for loop for (int i = 0; i &lt; collection.size(); i++) { T obj = collection.get(i); // snip } // using iterator Iterator&lt;T&gt; iter = collection.iterator(); while (iter.hasNext()) { T obj = iter.next(); // snip } // using iterator internally (confirm it yourself using javap -c) for (T obj : collection) { // snip } </code></pre> <p>Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible. </p> <p>Edit: I believe that micro-benchmarking is root of pretty much evil, just like early optimization. But then again, I think it's good to have a feeling for the implications of such quite trivial things. Hence I've run <a href="http://pastebin.com/f3a2ebd05" rel="noreferrer">a small test</a>: </p> <ul> <li>iterate over a LinkedList and an ArrayList respecively</li> <li>with 100,000 "random" strings</li> <li>summing up their length (just something to avoid that compiler optimizes away the whole loop)</li> <li>using all 3 loop styles (iterator, for each, for with counter)</li> </ul> <p>Results are similar for all but "for with counter" with LinkedList. All the other five took less than 20 milliseconds to iterate over the whole list. Using <code>list.get(i)</code> on a LinkedList 100,000 times took more than 2 minutes (!) to complete (60,000 times slower). Wow! :) Hence it's best to use an iterator (explicitly or implicitly using for each), especially if you don't know what type and size of list your dealing with. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload