Java Reference
In-Depth Information
1 import java.util.NoSuchElementException;
2
3 // TreeIterator class; maintains "current position"
4 //
5 // CONSTRUCTION: with tree to which iterator is bound
6 //
7 // ******************PUBLIC OPERATIONS**********************
8 // first and advance are abstract; others are final
9 // boolean isValid( ) --> True if at valid position in tree
10 // AnyType retrieve( ) --> Return item in current position
11 // void first( ) --> Set current position to first
12 // void advance( ) --> Advance (prefix)
13 // ******************ERRORS*********************************
14 // Exceptions thrown for illegal access or advance
15
16 abstract class TreeIterator<AnyType>
17 {
18 /**
19 * Construct the iterator. The current position is set to null.
20 * @param theTree the tree to which the iterator is bound.
21 */
22 public TreeIterator( BinaryTree<AnyType> theTree )
23 { t = theTree; current = null; }
24
25 /**
26 * Test if current position references a valid tree item.
27 * @return true if the current position is not null; false otherwise.
28 */
29 final public boolean isValid( )
30 { return current != null; }
31
32 /**
33 * Return the item stored in the current position.
34 * @return the stored item.
35 * @exception NoSuchElementException if the current position is invalid.
36 */
37 final public AnyType retrieve( )
38 {
39 if( current == null )
40 throw new NoSuchElementException( );
41 return current.getElement( );
42 }
43
44 abstract public void first( );
45 abstract public void advance( );
46
47 protected BinaryTree<AnyType> t; // The tree root
48 protected BinaryNode<AnyType> current; // The current position
49 }
figure 18.24
The tree iterator abstract base class
Search WWH ::




Custom Search