Java Reference
In-Depth Information
Note that the concrete type information is required in two places here:
in the type declaration of
strCell
and as part of the constructor invoca-
tion.
Of course, our cells aren't used directly like this; rather, they are an in-
ternal part of the
SingleLinkQueue
class, which would look like this:
class SingleLinkQueue<E> {
protected Cell<E> head;
protected Cell<E> tail;
public void add(E item) {
Cell<E> cell = new Cell<E>(item);
if (tail == null)
head = tail = cell;
else {
tail.setNext(cell);
tail = cell;
}
}
public E remove() {
if (head == null)
return null;
Cell<E> cell = head;
head = head.getNext();
if (head == null)
tail = null; // empty queue
return cell.getElement();
}
}
A queue with element type
E
is made up of cells of
E
. Again, everywhere
in the original class that
Object
was used, the type variable
E
is now
used. In addition, each use of
Cell
is replaced with
Cell<E>
.
You can create and use a queue of
String
objects as follows: