Java Reference
In-Depth Information
already declared as part of the outer list class. But we do have to say that it imple-
ments Iterator<E> to match the interface from java.util . Accidentally declaring
the inner class as ArrayListIterator<E> actually creates a second generic type E
and leads to confusing compiler errors.
Inner classes are normally declared to be private. Using an inner class for the iterator
is the more usual approach. It allows you to eliminate the field that keeps track of the
list. As we indicated in the definition box, when you declare an inner class, the
instances of the inner class have access to the methods and fields of the instance of
the outer class that constructed it. For example, the old version of the hasNext
method refers to a field called list that was used to keep track of the list over which
the iterator was iterating:
public boolean hasNext() {
return position < list.size();
}
This code can be simplified. Because the iterator class is now an inner class, you
can write the hasNext method in a simple way:
public boolean hasNext() {
return position < size();
}
This method is calling the size method even though the iterator has no such method.
Because it has no such method, it calls the ArrayList method of the outer class.
This can cause problems in one part of the code. When you write the remove
method for the iterator, you need to call the remove method of the list:
public void remove() {
if (!removeOK) {
throw new IllegalStateException();
}
remove(position - 1); // illegal
position--;
removeOK = false;
}
Unfortunately, this version does not compile, because both the iterator and the
list have a method called remove . One has no parameters and the other has one
parameter, so you'd think that Java could tell the difference, but it can't. You have to
use a special notation to make it clear that you want to refer to the outer object. You
do that by referring to the this value of the outer class, which you refer to as
ArrayList.this . Thus, you can rewrite the following line of code:
remove(position - 1);
 
Search WWH ::




Custom Search