Java Reference
In-Depth Information
String nextName = countingIterator.next();
if
(currentName.equals(nextName))
nameCount++;
}
// end while
System.out.println(currentName + " occurs " + nameCount + " times.");
}
// end while
To reset
countingIterator
to the list's beginning, we call the constructor again, since
Iterator
does not have a method for this purpose.
With the names given in Figure 15-4, these statements produce the following output:
Brad occurs 2 times.
Jane occurs 3 times.
Bob occurs 1 times.
Jane occurs 3 times.
Bette occurs 1 times.
Brad occurs 2 times.
Jane occurs 3 times.
Brenda occurs 1 times.
As you can see, since
nameIterator
(your left hand) encounters
Brad
twice and
Jane
three times,
the computation in the inner loop is repeated needlessly. For example, we compute that
Brad
occurs
twice each time
nameIterator
encounters
Brad
.
If
SeparateIterator
supports a remove operation, and if we are allowed to destroy the list, we
can remove the duplicate entries—and thereby prevent the repeated computations—by modifying
the
if
statement as follows:
if
(currentName.equals(nextName))
{
nameCount++;
if
(nameCount > 1)
countingIterator.remove();
}
// end if
When
nameCount
exceeds 1,
nextName
must be a name that the iterator
countingIterator
has
retrieved from the list more than once. Thus, we remove that entry so that
nameIterator
will not
encounter it. We do so by invoking
countingIterator.remove().
The iterator
countingIterator
then continues with the next entry. Exercise 8 at the end of this chapter considers the case when we
cannot destroy the list.
We will now examine an implementation of the public class
SeparateIterator
used in the previ-
ous examples. This class implements the interface
java.util.Iterator
.
15.12
An outline of the class
SeparateIterator
.
In the previous examples, we connect an iterator—
which is an instance of the class
SeparateIterator
—with a list by invoking the class's construc-
tor. To accomplish this connection, the class needs a data field that references the list. As you can
see in Listing 15-2, the constructor assigns this reference to the field. Also, notice that we make the
definition of
SeparateIterator
independent of a particular implementation of the list, such as
AList
or
LList
, by defining the field
list
as an instance of
ListInterface
.
In addition to connecting the iterator to the list in question, the constructor initializes it so the itera-
tion will begin at the first entry in the list. To enable this, the class has another data field
nextPosition