Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The first of the two you specify is a classic C <code>for</code> loop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example:</p> <pre><code>for (int i=0; i &lt; N : i++) </code></pre> <p>There are many more instances in code where the <code>for</code> was use to iterate over collections: </p> <pre><code>for (Iterator iter = myList.iterator(); iter.hasNext();) </code></pre> <p>To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the <a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf" rel="noreferrer">Generics</a> introduced in Java 1.5, the second of your two examples - the enhanced for loop, or the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="noreferrer"><code>for-each loop</code></a> - was introduced. </p> <p>The second is used with arrays and Generic collections. <a href="http://java.sun.com/developer/JDCTechTips/2005/tt0505.html#2" rel="noreferrer">See this documentation</a>. It allows you to iterate over a generic collection, where you know the type of the <code>Collection</code>, without having to cast the result of the <code>Iterator.next()</code> to a known type.</p> <p>Compare:</p> <pre><code>for(Iterator iter = myList.iterator; iter.hasNext() ; ) { String myStr = (String) iter.next(); //...do something with myStr } </code></pre> <p>with </p> <pre><code>for (String myStr : myList) { //...do something with myStr } </code></pre> <p>This 'new style' for loop can be used with arrays as well:</p> <pre><code>String[] strArray= ... for (String myStr : strArray) { //...do something with myStr } </code></pre>
    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