I want to create a program which dynamically creates multidimensional arrays, i.e. the program does not know how many dimensions the array will have as this is specified upon execution.
It is possible to create such arrays by using Array.newInstance(), this method returns an Object and it must be typecasted if being used as in the example.Code:import java.lang.reflect.*; class Stuff { public static void main(String[] args) { int[] dimensions = new int[Integer.parseInt(args[0])]; for (int i = 0; i < dimensions.length; i++) { dimensions[i] = 10; } int[][][][] stuff = (int[][][][])Array.newInstance(int.class, dimensions); stuff[9][8][9][9] = 8; } }
For example:
This will create a 4 dimensional array with 10 elements in each 'dimension'.Code:int[] dimensions = {10, 10, 10, 10}; int[][][][] stuff = (int[][][][])Array.newInstance(int.class, dimensions);
Now the problem is that having to use the constructor int[][][][] defeats the point of that method, as one still has to know how many dimensions the array will have.
Does anybody know how to avoid this?
As stated, I want a program that creates an n-dimensional array, where n is specified by the user.




Reply With Quote