Is it possible to create an two-dimensional array of a generic type parameter with only a size specified in Java?
To illustrate, can we create an array like this:
T[][] array = new T[x][];
Is it possible to create an two-dimensional array of a generic type parameter with only a size specified in Java?
To illustrate, can we create an array like this:
T[][] array = new T[x][];
You mention "generic" in your question and use the identifier T for your type, so I'm going to assume you are talking about creating an array of a generic type parameter.
You can't do that in Java. Arrays and generics don't mix very well. You can do it with reflection (see this question) but you might have an easier time doing this with a collection class instead. It would be a List of Lists, to get a 2D ragged container.
Not with generics, but using a known class it is possible. For generic i would recommend using ArrayList or similar.
String[][] array = new String[2][];
It can be used in this way:
array[0] = new String[1];
array[1] = new String[4];
array[0][0] = "Hello 0,0";
array[1][1] = "Hello 1,1 ";
System.out.println(array[0][0]);
System.out.println(array[1][1]);
You want a generic multidimensional array. You cannot create one. However, you can create an Object
array and then cast it. This is the "usual" way of creating generic arrays:
@SuppressWarnings("unchecked")
T[][] array = (T[][])new Object[x][];
You need @SuppressWarnings("unchecked")
because the cast is not safe and checked. From a typetheoretic point of view, it is even "wrong" (an array of type Object
is NOT an array of T
), but Java's type system has this inconsistency and this is the way to handle it.