}
public void setNext(Cell
this.next = next;
}
}
The class is now declared as Cell
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
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
protected Cell
public void add(E item) {
Cell
if (tail == null)
head = tail = cell;
else {
tail.setNext(cell);
tail = cell;
}
}
public E remove() {
if (head == null)
return null;
Cell
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