Java Reference
In-Depth Information
and print the objects in the collection to the command window. The first iter-
ator uses the
while
loop, the second one uses a
for
loop, but they both do the
same thing.
As of Java 5.0, there is another way to work your way through a collection,
one that requires less type casting, but more importantly one that can enforce
the type of objects at compile time.
Notice in Example 3.14 that the result of the
next()
is coerced into type
String
. That's because everything coming from the iterator (via the
next()
method) comes to us as a generic object. That way an iterator can handle any
type of object, but that also means that it is up to the application program to
know what type should be coming back from the iterator. Any typecasting error
won't be found until runtime.
With the syntax added in 5.0, not only is there a shorthand in the
for
loop for looping with an iterator. There is also syntax to tell the compiler explic-
itly what type of objects you are putting into your collection or array so that
the compiler can enforce that type.
Example 3.15 may help to make this clearer.
Example 3.15
Using a
for
loop iterator
import java.util.*;
public class
Foreign
{
public static void
main(String [] args)
{
List <String> loa = Arrays.asList(args);
System.out.println("size=" + loa.size());
for(String str : loa) {
System.out.println("arg=" + str);
}
} // main
} // Foreign
Here we build a
List
from the arguments supplied on the command line.
Notice the type name inside of angle brackets (less-than and greater-than signs).