Java Reference
In-Depth Information
6.5.1 the ListIterator interface
As shown in Figure 6.17, ListIterator is just like an Iterator , except that it
is bidirectional. Thus we can both advance and retreat. Because of this, the
listIterator factory method that creates it must be given a value that is log-
ically equal to the number of elements that have already been visited in the
forward direction. If this value is zero, the ListIterator is initialized at the
front, just like an Iterator . If this value is the size of the List , the iterator is
initialized to have processed all elements in the forward direction. Thus in
this state, hasNext returns false, but we can use hasPrevious and previous to
traverse the list in reverse.
Figure 6.18 illustrates that we can use itr1 to traverse a list in the forward
direction, and then once we reach the end, we can traverse the list backwards. It also
illustrates itr2 , which is positioned at the end, and simply processes the ArrayList
in reverse. Finally, it shows the enhanced for loop.
One difficulty with the ListIterator is that the semantics for remove must
change slightly. The new semantics are that remove deletes from the List the last
ListIterator is a
bidirectional ver-
sion of Iterator .
1 package weiss.util;
2
3 /**
4 * ListIterator interface for List interface.
5 */
6 public interface ListIterator<AnyType> extends Iterator<AnyType>
7 {
8 /**
9 * Tests if there are more items in the collection
10 * when iterating in reverse.
11 * @return true if there are more items in the collection
12 * when traversing in reverse.
13 */
14 boolean hasPrevious( );
15
16 /**
17 * Obtains the previous item in the collection.
18 * @return the previous (as yet unseen) item in the collection
19 * when traversing in reverse.
20 */
21 AnyType previous( );
22
23 /**
24 * Remove the last item returned by next or previous.
25 * Can only be called once after next or previous.
26 */
27 void remove( );
28 }
figure 6.17
A sample
ListIterator
interface
 
Search WWH ::




Custom Search