Iterating a Collection

   

The collections framework introduced the concept of iterators to take the place of the Enumeration interface for traversing the elements of a collection. The iterators are defined using interfaces just like Enumeration, but they differ in their method names , and they optionally allow you to remove elements from a collection while it is being iterated.

The Iterator Interface

An Iterator can be obtained for any object that implements the Collection interface. This interface defines three methods for traversing a collection:

 boolean hasNext() Object next() void remove() 

These methods allow you to check the iteration for more elements, retrieve the next element, and remove the last retrieved element from the collection. The next method throws a NoSuchElementException if called when the iteration has completed, which makes it important to always check hasNext first. The remove method is optional; it throws an UnsupportedOperationException if it is not a part of the Iterator being used.

Listing 10.5 shows a typical block of code used with an iterator. As you can see, obtaining and using an Iterator instance is simple. You do need to be aware of the object types held by a collection, however. The code shown here relies on the collection holding only instances of Address. A more robust implementation would check the type of each object before performing the cast operation.

Listing 10.5 Address.java ” Iterating a Collection
 import java.util.*; public class Address {   public String addressLine1;   public String addressLine2;   public String city;   public String state;   public String zip;   public Address( String line1, String line2, String city,    String state, String zip ) {     addressLine1 = line1;     addressLine2 = line2;     this.city = city;     this.state = state;     this.zip = zip;   }   public static void main( String args[] ) {     HashSet set = new HashSet();     set.add( new Address("123 Peachtree St", "", "Atlanta", "GA", "30305") );     set.add( new Address("100 Main St", "", "Any Town", "NY", "10101") );     // retrieve an iterator from the collection     Iterator iter = set.iterator();     while ( iter.hasNext() ) {   // loop while elements remain       // elements are returned as Object so cast to subtype       Address add = (Address)iter.next();       System.out.println( add.zip );     }   } } 

The ListIterator Interface

An Iterator makes no assumptions about the underlying behavior of the collection it iterates, so it is limited to the basic functionality shown in the preceding example. For more interesting operations, a List has the capability to provide a more specific form of the Iterator. The ListIterator takes advantage of the indexing in the List to allow you to perform several additional operations.

To start with, a ListIterator allows you to insert a new object into a List, or replace an existing one during its iteration. The add method inserts a new object immediately before the one that would be returned by a call to next. The set method replaces the last object returned by the iterator with the one specified. Both of these methods are optional and rely on the associated List being modifiable:

 void add(Object o) void set(Object o) 

The methods defined by Iterator allow you to move only forward through a collection. A ListIterator also allows you to move backward through a list using hasPrevious and previous the same way you use hasNext and next:

 boolean hasPrevious() Object previous() 

Finally, because you're looking at a List, you can also get the index values of the next or previous elements:

 int nextIndex() int previousIndex() 

Efficient Searching

Iterating a collection is useful when you need to do something with each element it contains, but it is not an efficient way to locate a particular object. If you have a sorted List, you can take advantage of the binarySearch methods provided by the Collections class to efficiently locate a specific object in a collection. One form of binarySearch relies on the natural ordering of the elements, and the other allows you to associate a Comparator:

 static int binarySearch(List list, Object key) static int binarySearch(List list, Object key, Comparator c) 

These methods perform a binary search, or ”if the List implements AbstractSequentialList ” a sequential search, to locate the specified key.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net