THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

AbstractQueue has the same requirements as AbstractCollection, with the additional requirements
that you must implement offer, poll, and peek.


AbstractList requires you to implement only size and get(int) to define an unmodifiable list class.
If you also override set(int,Object) you will get a modifiable list, but one whose size cannot change.
Your list can change size if you also override the methods add(int,Object) and remove(int).


For example, suppose you need to view a bunch of arrays as a single list. You could use one of the existing
List implementations, but at the cost of copying the information each time from the arrays into a new
collection. You could instead subclass AbstractList to create an ArrayBunchList type that lets you
do this without copying:


public class ArrayBunchList extends AbstractList {
private final E[][] arrays;
private final int size;


public ArrayBunchList(E[][] arrays) {
this.arrays = arrays.clone();
int s = 0;
for (E[] array : arrays)
s += array.length;
size = s;
}


public int size() {
return size;
}


public E get(int index) {
int off = 0; // offset from start of collection
for (int i = 0; i < arrays.length; i++) {
if (index < off + arrays[i].length)
return arrays[i][index - off];
off += arrays[i].length;
}
throw new ArrayIndexOutOfBoundsException(index);
}


public E set(int index, E value) {
int off = 0; // offset from start of collection
for (int i = 0; i < arrays.length; i++) {
if (index < off + arrays[i].length) {
E ret = arrays[i][index - off];
arrays[i][index - off] = value;
return ret;
}
off += arrays[i].length;
}
throw new ArrayIndexOutOfBoundsException(index);
}
}


When an ArrayBunchList is created, all the constituent arrays are remembered internally in the arrays
field, and the total size of the collection in size. ArrayBunchList implements size, get, and set, but
not add or remove. This means that the class provides a modifiable list, but one whose size cannot be
changed. Any call that needs values from the underlying arrays will go through get. Any action that modifies
the value of the ArrayBunchList will go through set, which modifies the appropriate underlying array.


AbstractList provides Iterator and ListIterator implementations on top of the other methods
of the class. Because the iteration implementations use the methods of your underlying subclass of

Free download pdf