Two ways of using Iterator

When the for-each loop is not available, and an explicit Iterator is needed, then iteration over a collection may be done with a while loop or a for loop.

The two styles have different advantages :

Example

import java.util.*;

public final class LoopStyles {

  public static void main( String... aArguments ) {
    List<String> flavours = new ArrayList<String>();
    flavours.add("chocolate");
    flavours.add("strawberry");
    flavours.add("vanilla");

    useWhileLoop( flavours );

    useForLoop( flavours );
  }

  private static void useWhileLoop( Collection<String> aFlavours ) {
    Iterator<String> flavoursIter = aFlavours.iterator();
    while ( flavoursIter.hasNext() ){
      System.out.println( flavoursIter.next() );
    }
  }

  /**
  * Note that this for-loop does not use an integer index.
  */
  private static void useForLoop( Collection<String> aFlavours ) {
    for ( Iterator<String> flavoursIter = aFlavours.iterator(); flavoursIter.hasNext(); ) {
      System.out.println( flavoursIter.next() );
    }
  }
} 



See Also :
Iterate without an index
Use for-each liberally
Would you use this technique?
Yes   No   Undecided   
© 2013 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on August 30, 2012.
Over 2,400,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -