As the program shows, it's valid to declare a reference to an array of type T, as this line does:
T vals; // OK
But, you cannot instantiate an array of T, as this commented-out line attempts:
// vals = new T; // can't create an array of T
The reason you can't create an array of T is that T does not exist at run time, so there is no
way for the compiler to know what type of array to actually create.
However, you can pass a reference to a type-compatible array to Gen( ) when an object
is created and assign that reference to vals, as the program does in this line:
vals = nums; // OK to assign reference to existent array
This works because the array passed to Gen has a known type, which will be the same type
as T at the time of object creation.
Inside main( ), notice that you can't declare an array of references to a specific generic type.
That is, this line
// Gen<Integer> gens = new Gen<Integer>; // Wrong!
won't compile. Arrays of specific generic types simply aren't allowed, because they can lead
to a loss of type safety.
You can create an array of references to a generic type if you use a wildcard, however,
as shown here:
Gen<?> gens = new Gen<?>; // OK
This approach is better than using an array of raw types, because at least some type checking
will still be enforced.
Generic Exception Restriction
A generic class cannot extend Throwable. This means that you cannot create generic exception
Final Thoughts on Generics
Generics are a powerful extension to Java because they streamline the creation of type-safe,
reusable code. Although the generic syntax can seem a bit overwhelming at first, it will
become second nature after you use it a while. Generic code will be a part of the future for
all Java programmers.
Search WWH :