HangingParens
HangingParens

Reputation: 61

Problems with an array of class containing generic members

When I compile this code:

public class OuterClass<T>
{
    class InnerClass
    {
       T temp;
    }
    
    private InnerClass[] theArray;
    
    public OuterClass(int size){
       this.theArray = new InnerClass[size];
  }
}

I get this error:

OuterClass.java:10: error: generic array creation
      this.theArray = new InnerClass[size];

So my question #1 is: why is creating an array of InnerClass a problem? After all, it's an array of objects, not of a generic type.

My question #2 is: why does modifying the code (see below) resolve the problem?

public class OuterClass<T>
{
    class InnerClass<U>  //changed this line
    {
       T temp;
    }
    
    private InnerClass<T>[] theArray;  //changed this line
    
    public OuterClass(int size){
       this.theArray = new InnerClass[size];
  }
}

Upvotes: 4

Views: 57

Answers (2)

Sweeper
Sweeper

Reputation: 272770

Think about what type of array you are instantiating here. In the first case, it is a

OuterClass<T>.InnerClass[]

Note that this type is a parameterised type (<T>), and you are not allowed to create arrays of parameterised types.

In the second case, since the declaration of InnerClass is parameterised, the name "InnerClass" actually refers to a raw type (because you are not specifying the type arguments), and because it is a raw type, the type of array that you are creating becomes:

OuterClass.InnerClass[]

Note that OuterClass loses its type parameter too, because you are using a raw type. This is now not a parameterised type, so you are allowed to create such an array.

Upvotes: 4

Tarik
Tarik

Reputation: 11209

The following code would work as well:

public class OuterClass<T>
{
    class InnerClass<U>  //changed from T to U
    {
       U temp;
    }

    private InnerClass<T>[] theArray;

    public OuterClass(int size){
       this.theArray = new InnerClass[size];
  }
}

In the first case, T is not recognized as a type parameter in the inner class. In case 2, you have provided a type parameter that you have selected to also be T for the inner class, but in fact has nothing to do with the type parameter of the outer class.

Upvotes: 0

Related Questions