Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating generic two-dimensional array using Class object

I have generic type with Class<T> object provided in constructor. I want to create two-dimensional array T[][] in this constructor, is this however possible?

like image 856
Krzysztof Stanisławek Avatar asked Dec 01 '22 18:12

Krzysztof Stanisławek


2 Answers

Same as How to create a generic array in Java? but extended to 2D:

import java.lang.reflect.Array;

public class Example <T> {

    private final Class<? extends T> cls;

    public Example (Class<? extends T> cls) {
        this.cls = cls;
    }

    public void arrayExample () {
        // a [10][20] array
        @SuppressWarnings("unchecked")
        T[][] array = (T[][])Array.newInstance(cls, 10, 20);
        System.out.println(array.length + " " + array[0].length + " " + array.getClass());
    }

    public static final void main (String[] args) {
        new Example<Integer>(Integer.class).arrayExample();
    }

}

Note after reading JAB's comment above: To extend to more dimensions, just add []'s and dimension parameters to newInstance() (cls is a Class, d1 through d5 are integers):

T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);

See Array.newInstance() for details.

like image 174
Jason C Avatar answered Dec 11 '22 00:12

Jason C


You have to use reflection, but it's possible: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance%28java.lang.Class,%20int...%29

Creates a new array with the specified component type and dimensions.

like image 36
JAB Avatar answered Dec 10 '22 22:12

JAB