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];
  }
}


Read more here: https://stackoverflow.com/questions/66270872/problems-with-an-array-of-class-containing-generic-members

Content Attribution

This content was originally published by HangingParens at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: