Java Reference
In-Depth Information
throw new IllegalStateException("Illegal call to set(); " +
"next() or previous() was not called, OR "
"add() or remove() called since then.");
} // end set
Note: Implementing the entire interface ListIterator as an inner class is easier when the
associated ADT has an array-based implementation rather than a linked implementation. (See
Exercise 17.)
Note: An iterator of type ListIterator is simpler to implement when it does not support
the operations add , remove , and set . Such an iterator is useful, as it enables you to traverse a
list in both directions. We leave this implementation as an exercise.
Java Class Library: The Interface Iterable
In a sense, this entire chapter has been about the Java Class Library, since the interfaces Iterator
and ListIterator are components of it. This last section introduces the interface Iterable and
shows its relation to for-each loops and the interface java.util.List .
15.51
The package java.lang of the Java Class Library contains the interface Iterable . This interface
declares only one method, as Listing 15-10 shows.
LISTING 15-10
The interface java.lang.Iterable
package java.lang;
public interface Iterable<T>
{
/** @return an iterator for a collection of objects of type T */
Iterator<T> iterator()
} // end Iterable
The method iterator returns an iterator that adheres to the interface Iterator . This method
has the same purpose as our method getIterator , as declared in the interface ListWithIterator -
Interface in Segment 15.17. Recall that our classes LinkedListWithIterator (Segment 15.19)
and ArrayListWithIterator (Segment 15.24) implement ListWithIteratorInterface . These
classes could certainly implement the method iterator in addition to getIterator . To do so, we
could modify the definition of ListWithIteratorInterface , as shown in Listing 15.11.
LISTING 15-11
The interface ListWithIteratorInterface modified to extend
Iterable
import java.util.Iterator;
public interface ListWithIteratorInterface<T> extends ListInterface<T>,
Iterable<T>
{
public Iterator<T> getIterator();
} // end ListWithIteratorInterface
 
 
Search WWH ::




Custom Search