13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.2 Fundamental Language Elements71The purpose of an iterator, then, is to step through a collecti<strong>on</strong> <strong>on</strong>e itemat a time. Example 3.14 shows a collecti<strong>on</strong> being built from the arguments <strong>on</strong>the command line. Then two iterators are used to step through the collecti<strong>on</strong>Example 3.14 Using iteratorsimport java.util.*;public classIter8{public static voidmain(String [] args){// create a new (empty) ArrayListArrayList al = new ArrayList();// fill the ArrayList with argsfor(int i = 0; i < args.length; i++) {al.add(args[i]);}// use the iterator in the while loopIterator itr1 = al.iterator();while(itr1.hasNext()) {String <strong>on</strong>earg;<strong>on</strong>earg = (String) (itr1.next());System.out.println("arg=" + <strong>on</strong>earg);}// define and use the iterator in the for loop:for(Iterator itr2 = al.iterator(); itr2.hasNext(); ) {String <strong>on</strong>earg;<strong>on</strong>earg = (String) (itr2.next());System.out.println("arg=" + <strong>on</strong>earg);}} // main} // Iter8remove() method, something that Enumerati<strong>on</strong> doesn’t support. The Enumerati<strong>on</strong> classis still around, but less frequently used. It is <strong>on</strong>ly available from certain older utility classes.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!