Generic Restrictions
Generic Restrictions
Part I
involve creating objects of a type parameter, static members, exceptions, and arrays. Each
is examined here.
Gen() {
ob = new T(); // Illegal!!!
}
}
class Wrong<T> {
// Wrong, no static variables of type T.
static T ob;
Although you can’t declare static members that use a type parameter declared by the
enclosing class, you can declare static generic methods, which define their own type
parameters, as was done earlier in this chapter.
T vals[]; // OK
class GenArrays {
public static void main(String args[]) {
Integer n[] = { 1, 2, 3, 4, 5 };
// This is OK.
Gen<?> gens[] = new Gen<?>[10]; // OK
}
}
As the program shows, it’s valid to declare a reference to an array of type T, as this line
does:
T vals[]; // OK
The reason you can’t create an array of T is that 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>[10]; // Wrong!
won’t compile.
You can create an array of references to a generic type if you use a wildcard, however, as
shown here:
Part I
Gen<?> gens[] = new Gen<?>[10]; // OK
This approach is better than using an array of raw types, because at least some type
checking will still be enforced.