Java Reference
In-Depth Information
The purpose of an iterator, then, is to step through a collection one item
at a time. Example 3.14 shows a collection being built from the arguments on
the command line. Then two iterators are used to step through the collection
Example 3.14 Using iterators
import java.util.*;
public class
Iter8
{
public static void
main(String [] args)
{
// create a new (empty) ArrayList
ArrayList al = new ArrayList();
// fill the ArrayList with args
for(int i = 0; i < args.length; i++) {
al.add(args[i]);
}
// use the iterator in the while loop
Iterator itr1 = al.iterator();
while(itr1.hasNext()) {
String onearg;
onearg = (String) (itr1.next());
System.out.println("arg=" + onearg);
}
// define and use the iterator in the for loop:
for(Iterator itr2 = al.iterator(); itr2.hasNext(); ) {
String onearg;
onearg = (String) (itr2.next());
System.out.println("arg=" + onearg);
}
} // main
} // Iter8
remove() method, something that Enumeration doesn't support. The Enumeration class
is still around, but less frequently used. It is only available from certain older utility classes.
Search WWH ::




Custom Search