Java Reference
In-Depth Information
What about the next method? It is supposed to return the next value from the list
and then reset the position to be one later in the sequence, which you can accomplish
by simply incrementing the value:
public int next() {
int result = list.get(position);
position++;
return result;
}
But the method has an important precondition that you must consider. What
if a client calls next when the iterator has run out of values to return? The method
should throw an exception in that case. The convention in Java is to throw a
NoSuchElementException :
public int next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int result = list.get(position);
position++;
return result;
}
The final operation performed by an iterator is the remove method. The method is
supposed to remove the most recent value that was returned by next . The position
field keeps track of the next value to be returned by the iterator, so the value to be
removed is at index position - 1 :
public void remove() {
list.remove(position - 1);
...
}
Keep in mind what happens when you ask the ArrayIntList to remove that
value. All of the other values will be shifted one to the left in the list. That means that
position will no longer be positioned at the next value in the list. That value has
been shifted one to the left, so you have to decrement position to account for the
shift that has taken place:
public void remove() {
list.remove(position - 1);
position--;
}
 
Search WWH ::




Custom Search