Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: multidimensional generic array creation

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.)

like image 933
dsg Avatar asked Mar 26 '11 21:03

dsg


People also ask

Can you create generic arrays in Java?

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.

Why is generic array creation not allowed in Java?

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.

How do you initialize a generic array in Java?

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.

Can you create an array of generic type?

No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.


1 Answers

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];
like image 109
Bala R Avatar answered Sep 19 '22 05:09

Bala R