Java Reference
In-Depth Information
that tracks where we are in the iteration. This field is simply the integer position of the entry in the list
that the method
next
last returned. It is convenient to initialize this field to zero.
LISTING 15-2
An outline of the class
SeparateIterator
import
java.util.Iterator;
import
java.util.NoSuchElementException;
public
class
SeparateIterator<T>
implements
Iterator<T>
{
private
ListInterface<T> list;
private
int
nextPosition;
// position of entry last returned by next()
private
boolean
wasNextCalled;
// needed by remove
public
SeparateIterator(ListInterface<T> aList)
{
list = aList;
nextPosition = 0;
wasNextCalled =
false
;
}
// end constructor
< Implementations of the methods
hasNext
,
next
,
and
remove
go here >
. . .
}
// end SeparateIterator
Providing an iterator with a remove operation is optional; however, we shall do so here
because the previous examples used one. This desire complicates our class somewhat, because the
client must call the method
next
before each call to
remove
. This requirement isn't simply a pre-
condition. The
remove
method must throw an exception if it isn't met. Therefore, we need an addi-
tional data field—a boolean flag—that enables
remove
to check whether
next
was called. We name
this data field
wasNextCalled
. The constructor initializes this field to false.
15.13
The method
hasNext
.
The class
SeparateIterator
has no special access to the private data fields
of the class that implements the list. It is a client of the list and so can process the list only by using
the list's ADT operations. Figure 15-5 shows a separate class iterator with a reference to a list but
with no knowledge of the list's implementation. The implementations of the iterator methods will
use methods specified in
ListInterface
. The resulting implementations are rather straightforward
but take longer to execute, in general, than the implementation of an inner class iterator. For exam-
ple, the method
hasNext
calls the list's
getLength
method:
public
boolean
hasNext()
{
return
nextPosition < list.getLength();
}
// end hasNext
Question 5
What does the method
hasNext
return when the list is empty? Why?