public Object createMultidimensionalArray(int dimLength){
int[] lengths = new int[dimLength];
for(int i = 0; i < dimLength; i++)
lengths[i] = dimLength;
return Array.newInstance(int.class, lengths);
}
Usage example:
int[][][] array3D = (int[][][]) createMultidimensionalArray(3);
System.out.println(Arrays.deepToString(array3D));
Output:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
Explanation:
The function Array.newInstance(Class<?> componentType, int... dimensions)
takes as input the wanted array type and lengths of all dimensions.
dimensions
is an array that tells the function what size each dimension should be. To get a 4x4x4x4 array, the following code works:
int[] dimensions = {4, 4, 4, 4};
Object arrObj = Array.newInstance(int.class, dimensions);
int[][][][] arr = (int[][][][]) arrObj;
Array.newInstance(...)
returns an Object
which can be easily converted to the correct type.