Java Reference
In-Depth Information
15.18
Example: Using the iterator to display a list. Once again, let's create a list of strings. Since we've
defined the interface ListWithIteratorInterface that includes the method getIterator and the
methods of ListInterface , we can use it to create the new list:
ListWithIteratorInterface<String> myList =
new LinkedListWithIterator<String>();
We add entries to this list using the list's add methods, as we have done before.
We now can display the list by using an iterator. We first create an iterator object by invoking
the new list method getIterator :
Iterator<String> myIterator = myList.getIterator();
The resulting iterator is ready to access the first entry in the list.
We then write a loop like the one you saw in Segment 15.7:
while (myIterator.hasNext())
System.out.println(myIterator.next());
15.19
An outline of the class. Listing 15-4 outlines the class LinkedListWithIterator with its inner
classes IteratorForLinkedList and Node . We will define the methods declared in the interface
Iterator within the inner class IteratorForLinkedList . However, we will not give iterators the
ability to remove entries from the data collection.
LISTING 15-4
An outline of the class LinkedListWithIterator
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedListWithIterator<T> implements
ListWithIteratorInterface<T>
{
private Node firstNode;
private int numberOfEntries;
public LinkedListWithIterator()
{
clear();
} // end default constructor
< Implementations of the methods of the ADT list go here;
you can see them in Chapter 14, beginning at Segment 14.7 >
. . .
public Iterator<T> getIterator()
{
return new IteratorForLinkedList();
} // end getIterator
< Segment 15.20 begins a description of the following inner class.>
private class IteratorForLinkedList implements Iterator<T>
{
private Node nextNode;
 
Search WWH ::




Custom Search