![]() |
![]() |
For/In Loops with Java Tiger (J2SE 5.0)In previous versions of Java, in order to iterate through a collection of objects, you may of had to use the java.util.operator class, using code similar to the following:
for (Iterator i= list.iterator(); i.hasNext();)
{
Object listElement = i.next();
System.out.println((String)listElement);
}
You can see from the above example that the listElement is not strongly typed, and also, the
code itself lacks elegance. In Java Tiger, you can use a for/in loop thus:
for (String listElement : list )
{
System.out.println(listElement);
}
Rules for using for/in loops in Java Tiger
Limitations of the for/in loopThere are certain things that you cannot do with the for/in loop, and you will have to resort to using the old iterator pattern. Examples of such tasks include:
Further reading...For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest. Other websites on Java Tiger can be found at Links-for-Java. |