0

I have a reference to the type class Class<?>of the generic type Element and I want to create a two dimensional array Element[][] where the second dimension null. Is there a way to do this?

The code I have right now is:

Class<?> type = ...
int length = ...
Element[][] array = (Element[][]) Array.newInstance(type, length, 0);
for (int i=0; i < array.length; i++)
    array[i] = null;

Is there any way to do this without the loop and the extra allocated memory?

Edit ----

The second dimension being null means that its just an array of null references to arrays of Element. I am doing this so I can dynamically allocate the length of the second domension so that the arrays do not need to be the same length. So I can do something like this:

array[0] = (Element[]) Array.newInstance(type, 4);
array[1] = (Element[]) Array.newInstance(type, 1);
array[2] = (Element[]) Array.newInstance(type, 3);
array[3] = null;
array[4] = null;
array[5] = (Element[]) Array.newInstance(type, 8);

etc..

3
  • array[i] = null? Maybe you want to put null in each element of the 2nd dimension? What does Class<?> have to do with this? Your question is unclear. Commented Feb 21, 2016 at 3:57
  • What do you mean by second dimension null? Commented Feb 21, 2016 at 4:02
  • 1
    Element[][] array = new Element[length][]; Commented Feb 21, 2016 at 4:14

1 Answer 1

2

Try this.

Class<?> type = ...
int length = ...
Class<?> typeOneDimArray = Array.newInstance(type, 0).getClass();
Element[][] array = (Element[][])Array.newInstance(typeOneDimArray, length);

In general, if you want to create an N dimensional array, create an array of N-1 dimensional array.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, thank you. It still feels odd that you have to create another array though.
I think there is no standard API to get array class from element class. So I create an array instance and get class of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.