THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

AbstractList, the modifying methods of the iteration will properly reflect the modifiability of your class.


The Iterator implementations of AbstractList use get to read values. As you will note,
ArrayBunchList has a get that can do some significant work if the value is stored in one of the later
arrays. We can make get smarter than shown here to help with this work, but we can be even more efficient
for iteration because it accesses the data sequentially. Here is an optimized Iterator:


private class ABLIterator implements Iterator {
private int off; // offset from start of list
private int array; // array we are currently in
private int pos; // position in current array


ABLIterator() {
off = 0;
array = 0;
pos = 0;
// skip any initial empty arrays (or to end)
for (array = 0; array < arrays.length; array++)
if (arrays[array].length > 0)
break;
}


public boolean hasNext() {
return off + pos < size();
}


public E next() {
if (!hasNext())
throw new NoSuchElementException();
E ret = arrays[array][pos++];


// advance to the next element (or to end)
while (pos >= arrays[array].length) {
off += arrays[array++].length;
pos = 0;
if (array >= arrays.length)
break;
}
return ret;
}


public void remove() {
throw new UnsupportedOperationException();
}
}


This implementation uses our knowledge of the underlying data structures to know exactly where the next
element is coming from. This is more efficient than invoking get to implement the iterator's next. (It is also
written to handle empty arrays and an empty ArrayBunchList.)


You can often substantially increase the performance of a resizable list by overriding the protected
removeRange method, which takes two int parameters, min and max, and removes the elements starting
at min, up to but not including max. The clear method uses remove Range to remove elements from
lists and sublists. The default implementation is to invoke remove on each element one at a time. Many data
structures can do bulk removes much more efficiently.


AbstractSequentialList extends AbstractList to make it easier to implement lists that are
backed by a sequential access data store where moving from one element of the data to another requires
examining each element of the data. In such a store, random access requires work since you must traverse

Free download pdf