What is the correct way to declare a multidimensional array and assign values to it?
This is what I have:
int x = 5; int y = 5; String[][] myStringArray = new String [x][y]; myStringArray[0][x] = "a string"; myStringArray[0][y] = "another string";
Java doesn't have "true" multidimensional arrays.
For example, arr[i][j][k]
is equivalent to ((arr[i])[j])[k]
. In other words, arr
is simply an array, of arrays, of arrays.
So, if you know how arrays work, you know how multidimensional arrays work!
Declaration:
int[][][] threeDimArr = new int[4][5][6];
or, with initialization:
int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Access:
int x = threeDimArr[1][0][1];
or
int[][] row = threeDimArr[1];
String representation:
Arrays.deepToString(threeDimArr);
yields
"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"
Try replacing the appropriate lines with:
myStringArray[0][x-1] = "a string"; myStringArray[0][y-1] = "another string";
Your code is incorrect because the sub-arrays have a length of y
, and indexing starts at 0. So setting to myStringArray[0][y]
or myStringArray[0][x]
will fail because the indices x
and y
are out of bounds.
String[][] myStringArray = new String [x][y];
is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With