Java Reference
In-Depth Information
Figure 15-6 shows a list and the field nextPosition just before the call to next , just after the
call to next but before the call to remove , and just after the call to remove . Notice in Part b that next
increments nextPosition and then returns a reference to Chris , the entry at that position and the
next entry in the iteration. A call to remove in Part c removes the entry— Chris —at nextPosition .
Afterwards, the next entry— Dan in the figure—moves to the next lower-numbered position in the
list. Thus, remove must decrement nextPosition so that a subsequent call to next will return Dan .
FIGURE 15-6
A list and nextPosition (a) just before the call to next ; (b) just
after the call to next but before the call to remove ; (c) after the
call to remove
(a) Before next()
(b) After next() returns Chris
(c) After remove() removes Chris
Ashley
Brett
Chris
Dan
Emily
Ashley
Brett
Chris
Dan
Emily
Ashley
Brett
Dan
Emily
Iterator cursor
Iterator cursor
Iterator cursor
2
3
2
nextPosition
nextPosition
nextPosition
The following implementation of remove reflects this discussion.
public void remove()
{
if (wasNextCalled)
{
// nextPosition was incremented by the call to next(), so
// it is the position number of the entry to be removed
list.remove(nextPosition);
nextPosition--; // a subsequent call to next() must be
// unaffected by this removal
wasNextCalled = false ; // reset flag
}
else
throw new IllegalStateException("Illegal call to remove(); " +
"next() was not called.");
} // end remove
Note: Separate class iterators
A separate class iterator must access an ADT's data by using the public methods of the ADT.
However, certain ADTs, such as a stack, do not provide sufficient public access to their data to
make such an iterator possible. In addition, the typical separate class iterator takes longer to per-
form its operations than do other kinds of iterators because of the indirect access to the ADT's
data. On the other hand, the implementation of a separate class iterator is usually straightfor-
ward. You can also have several independent separate class iterators in existence at the same
time for a given ADT.
To provide an iterator for an ADT's implementation that exists and cannot be altered, you
might need to define a separate class iterator.
 
Search WWH ::




Custom Search