How do I make a multidimensional array of generic items in java?
Consider the class:
class A<T>
{
T t;
public A(T t) { this.t = t; }
}
When I try to create a multidimensional array:
A<String>[][] array = new A<String>[2][3];
I get the following error:
generic array creation
A<String>[][] array = new A<String>[2][3];
^
I tried the following:
A<String>[][] array = (A<String>[][]) (new Object[2]3]);
But that just throws: java.lang.ClassCastException
What's the fix?
(I anticipate people recommending to use lists. Please explain how to achieve this using arrays.)
Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.
If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.
Array#newInstance to initialize our generic array, which requires two parameters. The first parameter specifies the type of object inside the new array. The second parameter specifies how much space to create for the array.
No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
I was able to do something like this
@SuppressWarnings("unchecked")
A<String>[][] array = (A<String>[][]) Array.newInstance(new A<String>("dummy").getClass(), 2, 3);
EDIT:
from @dsg's suggestion the following skips the creation of a temporary object.
@SuppressWarnings("unchecked")
A<String>[][] array = (A<String>[][]) Array.newInstance(A.class, 2, 3);
or (from @irreputable's suggestion)
@SuppressWarnings("unchecked")
A<String>[][] array = new A[2][3];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With