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 :
- the while loop is considerably more legible
- the for loop minimizes the scope of the Iterator to the loop itself
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 :
Would you use this technique?
|
|