Generic Array Restrictions

You cannot instantiate an array whose base type is a type parameter. You cannot create an array of type specific generic references.

The following short program shows both situations:

 
class MyClass<T extends Number> {
  T ob;
  T vals[];

  MyClass(T o, T[] nums) {
    ob = o;
    vals = nums;
  }
}

public class Main {
  public static void main(String args[]) {
    Integer n[] = { 1 };
    MyClass<Integer> iOb = new MyClass<Integer>(50, n);
    // Can't create an array of type-specific generic references.
    // Gen<Integer> gens[] = new Gen<Integer>[10]; 
    MyClass<?> gens[] = new MyClass<?>[10]; // OK
  }
}
  
Home 
  Java Book 
    Language Basics  

Generics:
  1. Generic Class
  2. Generic Bounded Types
  3. Generic Wildcard Arguments
  4. Generic Bounded Wildcards
  5. Generic Method
  6. Generic Constructors
  7. Generic Interfaces
  8. Raw Types and Legacy Code
  9. Generic Class Hierarchies
  10. Run-Time Type Comparisons Within a Generic Hierarchy
  11. Overriding Methods in a Generic Class
  12. Generic Restrictions
  13. Generic Array Restrictions