Java Reference
In-Depth Information
public final void clear()
{
firstNode = null ;
numberOfEntries = 0;
nextNode = null ;
} // end clear
< Implementations of the remaining methods of the ADT list go here;
you can see them in Chapter 14, beginning at Segment 14.7.>
. . .
< Implementations of the methods in the interface Iterator go here;
you can see them in Segments 15.21 through 15.23.>
. . .
public void resetTraversal()
{
nextNode = firstNode;
} // end resetTraversal
< Implementation of the private class Node (Listing 3-4 of Chapter 3) goes here.>
} // end ListWithTraversal
15.30
Example: Traversing a list. If myList is an instance of the previous class ListWithTraversal , it
has methods of the ADT list as well as the methods in Iterator . Thus, if we add strings to myList
using invocations such as myList.add("Chris") , we can display the list as follows:
myList.resetTraversal();
while (myList.hasNext())
System.out.println(myList.next());
Invoking resetTraversal is essential to set the traversal to the beginning of the list. Notice that
you use the list myList , not a separate iterator object, to invoke the Iterator methods. The reverse
was true in Segments 15.7 and 15.18.
Question 12 Revise the method displayList , as shown in Listing 12-2 of Chapter 12, for use
in a client of the class ListWithTraversal by using the approach of the previous example to
display the list. Is there any disadvantage to this implementation? Explain.
Question 13 Suppose that you want to omit the method resetTraversal .
a.
Could the default constructor initialize nextNode to firstNode ? Explain.
b.
Could the add methods initialize nextNode to firstNode ? Explain.
15.31
What's wrong with this approach? Although these traversal methods can execute quickly
because they have direct access to the underlying data structure of the list, including them as list
operations has disadvantages. Only one traversal can be in progress at a time. Moreover, an opera-
tion like resetTraversal , which is not in the interface Iterator , is necessary to initialize the tra-
versal. The resulting ADT has too many operations; it suffers from interface bloat .
With a little additional programming effort, you can organize the iterator methods as an inner
class. In doing so, you retain the speed of execution and suffer none of the disadvantages.
 
Search WWH ::




Custom Search