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();