Java Reference
In-Depth Information
types, and you find quite a number of these in the standard packages. You work with the Iterable<> and
Comparable<> generic interface types from the java.lang package later in this chapter.
To create a class from the generic type, LinkedList<> , you just supply an appropriate argument for the
parameter between the angled brackets. All occurrences of the type variable, T , that appear in the definition
are replaced by the type argument that you supply. This results in a class type that you can use to create an
object that implements a linked list that stores objects of the type that you specified, as illustrated in Figure
13-1 .
FIGURE 13-1
Thus, a generic type essentially defines a set of types, the set being produced by different arguments for
the parameters for the generic type. Note that although Figure 13-1 shows three types being defined, there
aren't three classes. There's just the generic class type to which you supply a type argument to produce a
particular type. The three types in Figure 13-1 are produced by plugging the three type arguments shown
into the generic type.
You can supply only a class or interface type such as type String or type Point as an argument for a type
parameter in a generic type. In other words, you cannot use a primitive type such as int or type double as an
argument, although, of course, you can use type Integer or type Double because these are class types that
wrap the corresponding primitive types. When you create a particular type from the generic type definition
by supplying an argument value for T , the argument is substituted for every occurrence of T in the generic
type specification. This applies to fields as well as the definitions of methods in the generic type.
You put a generic type definition in a source file with the extension .java , just like an ordinary class, so
you could save the code for the preceding outline generic type as LinkedList.java . It even compiles as it
is, although it's not very useful at the moment.
Implementing a Generic Type
You can easily convert the definition of the LinkedList class you were working with earlier into a generic
type. Here's how an initial stab at a LinkedList<> generic type definition looks:
public class LinkedList<T> {
// Default constructor - creates an empty list
public LinkedList() {}
// Constructor to create a list containing one object
 
 
Search WWH ::




Custom Search