Skip to content
Advertisement

How to dynamically declare shape of an Array in Java?

I am working with an API where I need to provide a Object[], Object[][], Object[][][]… you get the idea.

Assume setFoo requires an Object[], this is how I get it to work:

Object hello = "Hello";
Object world = "world";

final List<Object> objects = new ArrayList<>();
objects.add(hello);
objects.add(world);

// {"Hello", "world"}
item.setFoo(objects.toArray());

And this is how I make Object[][] requirement work, so that I can call setBar..

Object hello = "Hello";
Object world = "world";

// We now we need to stuff these into an Array of Arrays as in: {{Hello},{world}}
final List<Object> helloList = new ArrayList<>();
helloList.add(hello);

final List<Object> worldList = new ArrayList<>();
worldList.add(world);

final List<List<Object>> surroundingList = new ArrayList<>();
surroundingList.add(helloList);
surroundingList.add(worldList);

final Object[][] objects = new Object[surroundingList.size()][1];
for (int i = 0; i < surroundingList.size(); i++) {
    objects[i] = surroundingList.get(i).toArray();
}

item.setBar(objects);

The problem is, I am not able to figure out how to create the Object[][][] dynamically.. Is there a way to do this in Java? If I can make this final Object[][] objects = new Object[surroundingList.size()][1]; dynamic I should be in good hands.

Advertisement

Answer

You can’t do this with static code. The Java syntax and (compile time) type system doesn’t support the declaration or construction of arrays with indefinite dimensions.

You can create arrays with arbitrary dimensions using reflection; e.g.

int nosDimensions = 2;
Class<MyClass> clazz = MyClass.class;
Object array = java.lang.reflect.Array.newInstance(clazz, nosDimensions);

MyClass[][] typedArray = (MyClass[][]) array;  // just to show we can do it ...

But the problem is that if you go down the path, you are liable to end up:

  • doing lots of casting to types with definite dimensions (see typedArray above), and / or

  • doing operations on the arrays using messy reflective code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement