Java Reference
In-Depth Information
of the
size
and
iterator
methods. This means you must at least write
an implementation of
Iterator
for your collection. If your collection is
modifiable, you must also override the default implementation of the
add
method (which throws
UnsupportedOperationException
) and your iterator
must support
remove
.
AbstractSet
extends
AbstractCollection
, and the methods you must im-
plement and can override are the same, with the additional constraint
that a subclass of
AbstractSet
must conform to the contract of the
Set
interface. It also overrides the implemention of
equals
and
hashCode
from
Object
.
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
re-
move(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 collec-
tion. You could instead subclass
AbstractList
to create an
ArrayBunchList
type that lets you do this without copying:
public class ArrayBunchList<E> extends AbstractList<E> {
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;
}