1

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][];
Han Tuzun
  • 461
  • 5
  • 9
  • 3
    Have you simply tried it? It works. The compiler is your friend. – gexicide Sep 29 '14 at 08:09
  • @gexicide I tried for sure, but it does not work even for `T[] arr = new T[x];`. It gives `error: generic array creation`. – Han Tuzun Sep 29 '14 at 08:49
  • The problem is not the 2D jagged array. The problem is the type `T` which seems to be a generic type parameter. It is not possible to create arrays of generic type parameters. – gexicide Sep 29 '14 at 08:57
  • Right, I'm trying to create an array of a generic type parameter. I'll edit the question since it's ambigious. – Han Tuzun Sep 29 '14 at 09:00

3 Answers3

3

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.

Community
  • 1
  • 1
Daniel Earwicker
  • 108,589
  • 35
  • 194
  • 274
1

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]);
CodeTower
  • 6,148
  • 5
  • 27
  • 50
0

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.

gexicide
  • 35,369
  • 19
  • 80
  • 136
  • Thanks but I tried that without success. When I created and returned the same array with casting in a method, and I try store this result from when I call the method, I got an error that I can't store an Object[][] in a (let's say) Integer[][]. – Han Tuzun Oct 01 '14 at 05:54
  • @EmrehanTuzun: The behaviour you explain sounds strange. Please post your exact code that failed. (The method and the code that called it) – gexicide Oct 01 '14 at 10:55
  • here is the code that fails: http://pastebin.com/y9TLjJMx. I'm trying to generalise this gist: https://gist.github.com/emrehan/bc24dea0878dcfe5cdcb – Han Tuzun Oct 08 '14 at 13:29