Java Reference
In-Depth Information
PITFALL: (continued)
constructor has no type parameter in angular brackets. So, you see the following
in Display 14.5 :
public
Pair(T firstItem, T secondItem)
But as shown in Display 14.6, when you instantiate a generic class by specifying a
type for the type parameter, you do specify the type in angular brackets when writing
the constructor name, as in the following from Display 14.6:
Pair<String> secretPair =
new
Pair<String>("Happy", "Day");
However, this second case is not hard to remember. If you leave out the
<String>
, Java
would not know which
Pair
class you meant. If you leave out the
<String>
, the compiler
could not tell if you meant
Pair<String>
,
Pair<Double>
, or some other
Pair
class.
■
PITFALL: You Cannot Plug in a Primitive Type for a Type Parameter
The type plugged in for a type parameter must be a reference type. It cannot be a primitive
type such as
int
,
double
, or
char
. However, now that Java has automatic boxing, this
is not a big restriction in practice. For example, if you want
Pair<int>
, you cannot
have it, but you can have
Pair<Integer>
, and thanks to automatic boxing, you can use
Pair<Integer>
with
int
values. This is illustrated by the program in Display 14.7.
The most typical type to plug in for a type parameter is a class type. However, you
can plug in any reference type. So, in particular, you can plug in an array type for a
type parameter.
■
PITFALL: A Type Parameter Cannot Be Used Everywhere a Type
Name Can Be Used
Within the definition of a parameterized class definition, there are places where
an ordinary class name would be allowed but a type parameter is not allowed. In
particular, you cannot use the type parameter in simple expressions using
new
to
create a new object. For example, the following are all illegal within the definition of
a parameterized class definition with type parameter
T
:
T object =
new
T();
//The first T is legal,
//the second one is illegal.
T[] a =
new
T[10];
//The first T is legal,
//the second one is illegal.
This restriction is not as arbitrary as it might at fi rst appear. In the fi rst case,
T
is
not being used as a type name; it is being used as a constructor name. In the second
case,
T
is being used as something like a constructor, although it is not offi cially a
constructor.
■