2

I would like to create an instance of a (10x10) 2d array of generics:

objArray<T>[][] = new T[10][10]

Obviously, this doesn't work due to java's type erasure.

I've found this workaround that suggests, for a 1D array, something like:

// a generic class with a method to create an array of the parameterised type
public class GenericArrayTest<T>{

  // declare the class instance
  private Class<T> tClass;

  // code to initialise tClass

  // returns an array of the parameterised type
  public <T> T[] returnArray(){
    return (T[])java.lang.reflect.Array.newInstance(tClass, 10);
  }

}

This works for a 1D array, but when I modify it for a 2D array:

  public <T> T[][] returnArray(){
    return (T[][])java.lang.reflect.Array.newInstance(tClass, 10, 10);
  }

The second dimension is null. That is, T[1-10] are populated, but T[][1-10] are null. Can anyone suggests tips to fix this? If there's no straightforward way, I'll probably just bite the bullet and get rid of generics in my application :(

EDIT: *******

Helpful answers below allowed me to arrive at answer. My array declaration was indeed working correctly, but this only sets up an empty memory block. Had to instantiate an object for each value in array as such:

for (int i=0; i<10; i++){
    for (int j=0; j<10; j++){                
         myarray[i][j] = this.tClass.newInstance();
Community
  • 1
  • 1
Adam Hughes
  • 14,601
  • 12
  • 83
  • 122
  • "Can anyone suggests tips to fix this?" Not mixing generics and arrays. They really don't play nicely (e.g. what if `T` were `List`?) – Andy Turner Apr 26 '16 at 13:35

2 Answers2

1

Of course they are null, which instances should the method put in there?

An array is nothing else but a reserved series of memory addresses. The T[1-10][] part is initialized with instances of arrays of type T[]. The T[][1-10] is the array of pointers to the object - which are null. You still have to populate it with instances.

1-dim array

  • T[0] -> null
  • T[1] -> null

2-dim array

  • T[0] -> T[] {null, null,null, null ...}
    • T[0][0] -> null
    • T[0][1] -> null
Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
1
public class GenericArrayTest<T>{   

    private final Class<T> cls; 

    public GenericArrayTest (Class<T> cls) {
        this.cls = cls;
    }

    public <T> T[][] returnArray(){
    T[][] array = (T[][])Array.newInstance(cls,30,40);
    return array;
    }

i have made some changes to your code this might help you . check this

Priyamal
  • 2,919
  • 2
  • 25
  • 52