Java Reference
In-Depth Information
Defining an Iterator Class
In Display 15.17, we have rewritten the class LinkedList2 from Display 15.7 so that
it has an inner class for iterators and a method iterator( ) that returns an iterator
for its calling object. We have made the inner class List2Iterator public so that we
can have variables of type List2Iterator outside the class LinkedList2 , but we do
not otherwise plan to use the inner class List2Iterator outside of the outer class
LinkedList2 .
Use of iterators for the class LinkedList2 is illustrated by the program in
Display 15.18 . Note that, given a linked list named list , an iterator for list is
produced by the method iterator as follows:
LinkedList2.List2Iterator i = list.iterator( );
The iterator i produced in this way can only be used with the linked list named list .
Be sure to notice that outside of the class, the type name for the inner class iterator
must include the name of the outer class as well as the inner iterator class. The class
name for one of these iterators is
LinkedList2.List2Iterator
Display 15.17
A Linked List with an Iterator (part 1 of 3)
1 import java.util.NoSuchElementException;
This is the same as the class in Display 15.7 and
15.11 except that the List2Iterator inner class
and the iterator() method have been added.
2 public class LinkedList2
3 {
4 private class Node
5 {
6
private String item;
7
private Node link;
<The rest of the definition of the Node inner class is given in Display 15.7.>
8 } //End of Node inner class
9 /**
10 If the list is altered any iterators should invoke restart or
11 the iterator's behavior may not be as desired.
12 */
13 public class List2Iterator
14 {
15 private Node position;
16 private Node previous; //previous value of position
17 public List2Iterator( )
18 {
19 position = head; //Instance variable head of outer class.
20 previous = null ;
21 }
An inner class for iterators for
LinkedList2 .
 
Search WWH ::




Custom Search