Java Reference
In-Depth Information
So how do you implement the ArrayIntListIterator class? The main function
that the iterator performs is to keep track of a particular position in a list, so the
primary field will be an integer variable for storing this position:
public class ArrayIntListIterator {
private int position;
public ArrayIntListIterator(...) {
position = 0;
...
}
...
}
Initially you start position at 0 so that it will refer to the first value in the list.
The hasNext method is supposed to determine whether any values remain to iterate
over. To do so, it will have to compare this position to the size of the list:
public boolean hasNext() {
// check position against size of the list
}
To perform this comparison, the iterator needs to be able to find out the size of the
list. To do so, the iterator will need to keep track of the list over which it is iterating.
That means that you will need a second field and the constructor will have to be
passed a reference to the list to iterate over:
public class ArrayIntListIterator {
private ArrayIntList list;
private int position;
public ArrayIntListIterator(ArrayIntList list) {
this.list = list;
position = 0;
...
}
...
}
Using this field, you can now easily write the hasNext method:
public boolean hasNext() {
return position < list.size();
}
Search WWH ::




Custom Search