Java Reference
In-Depth Information
private
T
first;
private
S
second;
}
This completes the definition of the generic
Pair
class. It is now ready to use
whenever you need to form a pair of two objects of arbitrary types.
Use type variables for the types of generic fields, method parameters, and return
values.
As a second example, let us turn our linked list class into a generic class. This class
only requires one type variable for the element type, which we will call
E
.
public class LinkedList<E>
In the case of the linked list, there is a slight complication. Unlike the
Pair
class, the
LinkedList
class does not store the elements in its instance fields. Instead, a
linked list manages a sequence of nodes, and the nodes store the data. Our
LinkedList
class uses an inner class
Node
for the nodes. The
Node
class must be
modified to express the fact that each node stores an element of type
E
.
public class LinkedList<
E
>
{
. . .
private Node first;
private class Node
{
public
E
data;
public Node next;
}
}
The implementation of some of the methods requires local variables whose type is
variable, for example:
public
E
removeFirst()
{
if (first == null)
throw new NoSuchElementException();
E
element = first.data;
first = first.next;
return element;
}
769