Java Reference
In-Depth Information
770
Overall, the process is straightforward. Use the type E whenever you receive, return,
or store an element object. Complexities arise only when your data structure uses
helper classes, such as the nodes and iterators in a linked list. If the helpers are inner
classes, you need not do anything special. However, helper types that are defined
outside the generic class need to become generic classes as well.
Following is the complete reimplementation of our LinkedList class, as a generic
class with a type variable.
S YNTAX 17.2 Defining a Generic Class
accessSpecifier class
GenericClassName<TypeVariable 1 , TypeVariable 2 ,. . .
>
{
constructors
methods
fields
}
Example:
public class Pair< T, S>
{
. . .
}
Purpose:
To define a generic class with methods and fields that depend on type variables
ch17/genlist/LinkedList.java
1 import java.util.NoSuchElementException;
2
3 /**
4 A linked list is a sequence of nodes with
efficient
5 element insertion and removal. This class
6 contains a subset of the methods of the
standard
7 java.util.LinkedList class.
Search WWH ::




Custom Search