String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Pay special attention to how the list is displayed in reverse. After the list is modified, litr
points to the end of the list. (Remember, litr.hasNext( ) returns false when the end of the list
has been reached.) To traverse the list in reverse, the program continues to use litr, but this
time it checks to see whether it has a previous element. As long as it does, that element is
obtained and displayed.
The For-Each Alternative to Iterators
If you won't be modifying the contents of a collection or obtaining elements in reverse order,
then the for-each version of the for loop is often a more convenient alternative to cycling
through a collection than is using an iterator. Recall that the for can cycle through any collection
of objects that implement the Iterable interface. Because all of the collection classes implement
this interface, they can all be operated upon by the for.
The following example uses a for loop to sum the contents of a collection:
// Use the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Original contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home