Java Reference
In-Depth Information
15.9
Example.
The requirement that you invoke
next
before you call
remove
results in two situations that
cause the exception
IllegalStateException
. If
nameList
is defined as in the previous example, and
we write
nameIterator =
new
SeparateIterator<String>(nameList);
nameIterator.hasNext();
nameIterator.remove();
an
IllegalStateException
occurs because we did not call
next
before we called
remove
.
Similarly, if we write
nameIterator.next();
nameIterator.remove();
nameIterator.remove();
the second
remove
causes an
IllegalStateException
because
remove
had been called already
since the most recent call to
next
.
Question 1
Assume that
nameList
contains the names Jamie, Joey, and Rachel, as it does in
Segment 15.6. What output is produced by the following Java statements?
Iterator<String> nameIterator =
new
SeparateIterator<String>(nameList);
nameIterator.next();
nameIterator.next();
nameIterator.remove();
System.out.println(nameIterator.hasNext());
System.out.println(nameIterator.next());
Question 2
Assume that
nameList
is an instance of a class that implements
ListInterface
,
and
nameIterator
is defined as in the previous question. If
nameList
contains at least three
strings, write Java statements that display the list's third entry.
Question 3
Given
nameList
and
nameIterator
as described in the previous question, write
statements that display the even-numbered entries in the list. That is, display the second
entry, the fourth entry, and so on.
Question 4
Given
nameList
and
nameIterator
as described in Question 2, write state-
ments that remove all entries from the list.
Note:
Java's interface
java.util.Iterator
specifies three methods:
hasNext
,
next
, and
remove
. The method
hasNext
sees whether the iterator has a next entry to return. If so,
next
returns a reference to it. The method
remove
can remove the entry last returned by a call to
next
, or it can simply throw an
UnsupportedOperationException
if you choose to disallow
removals by the iterator.
15.10
Multiple iterators.
Although the previous examples show one iterator traversing a list, we can
have several iterations of the same list in progress simultaneously. For example, imagine a printed
list of names that are not distinct and are in no particular order. Running one finger down that list to
count the names is like having one iteration of a list. Now suppose that you want to count the num-
ber of times each name occurs in the printed list. You can use two fingers, as follows. With your left