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();
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 )
Rules for using for/in loops in Java Tiger
- The object collection being iterated must either inherit from java.lang.Iterable or be an array. Examples
of objects that inherit from java.lang.Iterable are the ArrayList, HashSet, List, and Set. When iterating with arrays, the compiler performs an optimization so that it has equal speed to a standard for/next loop.
- The loop variable must be defined within the for/in loop, it cannot be defined outside and passed in
- In order to iterate over a strongly-typed collection, you need to use generics to define the type of the collection prior to iterating over it. Therefore a List should be defined List<String> wordlist = new ArrayList<String>();
Limitations of the for/in loop
There 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:
- Determining the position within an arrayList as you are iterating through it - for example, if you wanted to show % processing complete...
- Removing elements from an arrayList as you are iterating through it.
- Iterate backwards through an arrrayList
- Iterate through two arrayLists in tandem
- Iterate using size() and get() calls rather than the iterator (this gives a performance gain)
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.
|Copyright 2006-2019. Infinite Loop Ltd