THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

}
public void setNext(Cell next) {
this.next = next;
}
}


The class is now declared as Cell (which is read as "Cell of E"). E represents the type of element that
a cell object can hold. In this generic version of Cell, everywhere that Object was used in the original
Cell class now uses the name E. E is known as a type variable for which a concrete type can be substituted.
There's nothing special about the name Eit could be ElementType, for examplebut E is a nice abbreviation
for "element." By convention, type variables have single character names: E for an element type, K for a key
type, V for a value type, T for a general type, and so forth.


To create an actual Cell object you have to tell the compiler what specific type you wish to replace E with.
For example, a Cell to hold a String could be constructed and referenced as follows:


Cell strCell = new Cell("Hello");


Note that the concrete type information is required in two places here: in the type declaration of strCell
and as part of the constructor invocation.


Of course, our cells aren't used directly like this; rather, they are an internal part of the SingleLinkQueue
class, which would look like this:


class SingleLinkQueue {
protected Cell head;
protected Cell tail;
public void add(E item) {
Cell cell = new Cell(item);
if (tail == null)
head = tail = cell;
else {
tail.setNext(cell);
tail = cell;
}
}


public E remove() {
if (head == null)
return null;
Cell 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.


You can create and use a queue of String objects as follows:


SingleLinkQueue queue =

Free download pdf