Java Reference
In-Depth Information
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 primi-
tive 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 particu-
lar, 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 parameter-
ized 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 first appear. In the first 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 officially a constructor.
PITFALL: An Instantiation of a Generic Class Cannot be an Array
Base Type
Arrays such as the following are illegal (the generic class Pair is the one defined in
Display 14.5):
Pair<String>[] a = new Pair<String>[10]; //Illegal
This is a reasonable thing to want to do, but it is not allowed because of technical
details having to do with how Java implements generic classes. The full explanation for
this restriction is beyond the scope of this topic.
Search WWH ::




Custom Search