Java Reference
In-Depth Information
public
ListIterator<T> getIterator()
{
return
new
IteratorForArrayList();
}
// end getIterator
private
class
IteratorForArrayList
implements
ListIterator<T>
{
< The description of this implementation begins with Segment 15.43. >
. . .
}
// end IteratorForArrayList
}
// end ArrayListWithListIterator
15.43
The data fields and constructor.
We begin implementing the inner class
IteratorForArrayList
by
thinking about how the methods
remove
and
set
will throw the exception
IllegalStateException
.
Both of these methods throw this exception for the same reasons, that is, if either
•
next
or
previous
was not called or
•
remove
or
add
has been called since the last call to
next
or
previous
Figure 15-11 shows calls to
remove
in various contexts that cause an
IllegalStateException
.
This aspect of the implementation might be intimidating at first, but it need not be difficult.
When we implemented
Iterator
's
remove
method in Segment 15.28, we tested the boolean data
field
wasNextCalled
to see whether
next
had been called. We could do that here and define analogous
FIGURE 15-11
Possible contexts in which the method
remove
of the iterator
traverse
throws an exception when called
Neither
next
nor p
revious
has been called
Causes an exception
(a)
traverse.remove();
(b)
traverse.next();
traverse.remove();
Legal
traverse.remove();
Causes an exception
(c)
traverse.previous();
traverse.remove();
Legal
Causes an exception
traverse.remove();
(d)
traverse.next();
traverse.add(...);
traverse.remove();
Causes an exception
(e)
traverse.previous();
traverse.add(...);
traverse.remove();
Causes an exception