Java Reference
In-Depth Information
itself. You can use the
this
keyword to say, “Construct an iterator that is iterating
over me”:
public ArrayIntListIterator iterator() {
return new ArrayIntListIterator(this);
}
You can find a complete listing of this fourth version of the
ArrayIntList
class
along with the
ArrayIntListIterator
class on the web page for this textbook at
In this section, we will explore how to convert the version of
ArrayIntList
from
the previous section into a generic
ArrayList<E>
. To start, you can simply replace
all occurrences of
ArrayIntList
with
ArrayList<E>
and change references to
int
that refer to values to
E
. Of course, there are other uses of
int
that specify capacity,
size, and indexes, and these don't change.
This approach almost works, but there are a few places where you have to be care-
ful. For example, when you define constructors, you don't use the generic
E
when
you're naming the constructor. So the zero-argument constructor becomes:
public ArrayList() {
this(DEFAULT_CAPACITY);
}
You also run into trouble in the second constructor. After you perform the simple
substitution, you end up with the following method:
public ArrayList(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity: " + capacity);
}
elementData = new E[capacity]; // illegal
size = 0;
}
When you try to compile this version, you get an error indicating that you are not
allowed to construct a generic array. This is a limitation of generic types. You can
construct an array of type
Object[]
, but not an array of type
E[]
. You can solve this
problem by introducing a cast. Replace the following line of code:
elementData = new E[capacity];
Search WWH ::
Custom Search