Java Reference
In-Depth Information
elementData[i] = elementData[i + 1];
}
size--;
}
You need to add an extra line of code after the shifting code that sets the unused
array element back to null :
public void remove(int index) {
checkIndex(index);
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
elementData[size - 1] = null;
size--;
}
Similarly, the clear method needs to set all values to null before resetting the
size field to 0 :
public void clear() {
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
One final change that you will see in this class is that the iterator class has been
converted to what is known as an inner class :
Inner Class
A class declared inside another class. Objects of the inner class have access
to the methods and fields of the outer class.
In other words, the structure becomes
public class ArrayList<E> {
...
private class ArrayListIterator implements Iterator<E> {
...
}
}
The generic syntax can be a bit confusing with inner classes. We declare our inner
ArrayListIterator class without an <E> type parameter, because the type E is
 
Search WWH ::




Custom Search