Reputation: 25
How can I make an array given the dimensions introduced by user??
For example, if you introduced 5(the dimensions) inside of that array we need an array of 4 dimensions, inside of it 3 dimensions and etc...
Please help!
Upvotes: 1
Views: 80
Reputation: 15497
You could use Array#newInstance
int[][][] ar = (int[][][]) Array.newInstance(int.class, 3, 2, 1);
System.out.println(Arrays.deepToString(ar));
or
int[] dimensionLengths = new int[numberOfDimensions];
Arrays.fill(dimensionLengths, 1);
Array.newInstance(int.class, dimensionLengths);
Upvotes: 2
Reputation: 393781
Since an array is an Object, an array of Object (Object[]) can itself hold arrays, and so on. This would require a lot of castings, and would be very un-type-safe and ugly, but it can be done.
For example :
Object[] arr3d = new Object[10]; // create the first dimension
arr3d[0] = new Object[20]; // create the second dimension
((Object[])arr3d[0])[0] = new Object[30]; // create the third dimension
...
I wouldn't recommend actually doing it, though.
Upvotes: 0