Datasheet

By constraining the T type parameter, invoking draw is acceptable because Java knows it’s a Shape.
If you want to specify multiple interfaces/classes to use as a bound, separate them with the ampersand
(
&). Also note that extends is used to specify bounds regardless of whether the type parameter is
bounded by an interface or a class.
Using Generics
It is straightforward to create objects of a generic type. Any parameters must match the bounds speci-
fied. Although you might expect to create an array of a generic type, this is only possible with the wild-
card type parameter. It is also possible to create a method that works on generic types. This section
describes these usage scenarios.
Class Instances
Creating an object of a generic class consists of specifying types for each parameter and supplying any
necessary arguments to the constructor. The conditions for any bounds on type variables must be met.
Note that only reference types are valid as parameters when creating an instance of a generic class.
Trying to use a primitive data type causes the compiler to issue an unexpected type error.
This is a simple creation of a
HashMap that assigns Floats to Strings:
HashMap<String,Float> hm = new HashMap<String,Float>();
Arrays
Arrays of generic types and arrays of type variables are not allowed. Attempting to create an array of
parameterized
Vectors, for example, causes a compiler error:
import java.util.*;
public class GenericArrayExample {
public static void main(String args[])
{
Vector<Integer> vectorList[] = new Vector<Integer>[10];
}
}
If you try to compile that code, the compiler issues the following two errors. This code is the simplest
approach to creating an array of a generic type and the compiler tells you explicitly that creating a
generic type array is forbidden:
GenericArrayExample.java:6: arrays of generic types are not allowed
Vector<Integer> vectorList[] = new Vector<Integer>[10];
^
GenericArrayExample.java:6: arrays of generic types are not allowed
Vector<Integer> vectorList[] = new Vector<Integer>[10];
^
2 errors
You can, however, create an array of any type by using the wildcard as the type parameter.
14
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 14