Java Reference
In-Depth Information
This method also has an important precondition to consider. A client is supposed
to call
next
before calling
remove
. One possibility is that the client will call
remove
before making any call on
next
. If that happens, it will be obvious from the fact that
position
will be zero. Another possibility is that the client will call
remove
twice in
a row without calling
next
in between. That is not a legal operation either. You won't
know just from looking at the value of
position
whether the client has violated this
precondition.
In this case, you need an extra bit of state for the object. You need to keep track of
whether it is currently legal to remove a value, so this is a good time to add a field. It
will be of type
boolean
and you can call it
removeOK
. You can use this field to throw
an exception if the precondition is violated. And once a call on
remove
has been per-
formed, you have to remember that it is no longer legal to remove a value until
next
is called again:
public void remove() {
if (!removeOK) {
throw new IllegalStateException();
}
list.remove(position - 1);
position--;
removeOK = false;
}
Notice that you throw an
IllegalStateException
because a call on the method
is not appropriate if it is not okay to remove a value. You can then add code to the
constructor to initialize this field to
false
, and you can reset it to
true
whenever
next
is called.
Here is the final class definition:
1 // Objects of this class can be used to iterate over an
2 // ArrayIntList and remove values from the list.
3
4
import
java.util.*;
5
6
public class
ArrayIntListIterator {
7
private
ArrayIntList list; // list to iterate over
8
private int
position; // current list position
9
private boolean
removeOK; // okay to remove now?
10
11 // post: constructs an iterator for the given list
12
public
ArrayIntListIterator(ArrayIntList list) {
13
this
.list = list;
14 position = 0;
15 removeOK = false;
Search WWH ::
Custom Search