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:
or, with initialization:
Access:
or
String representation:
yields
I'll add that if you want to read the dimensions, you can do this:
You can also have jagged arrays, where different rows have different lengths, so
a[0].length != a[1].length
.You can look at this to start off:
Multidimensional Array in Java
Returning a multidimensional array
Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...
We can define a two-dimensional array as:
int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}
int[ ][ ] num = new int[4][2]
If you don't allocate, let's say
num[2][1]
, it is not initialized and then it is automatically allocated 0, that is, automaticallynum[2][1] = 0
;Below,
num1.length
gives you rows.num1[0].length
gives you the number of elements related tonum1[0]
. Herenum1[0]
has related arraysnum1[0][0]
andnum[0][1]
only.Here we used a
for
loop which helps us to calculatenum1[i].length
. Herei
is incremented through a loop.Try replacing the appropriate lines with:
Your code is incorrect because the sub-arrays have a length of
y
, and indexing starts at 0. So setting tomyStringArray[0][y]
ormyStringArray[0][x]
will fail because the indicesx
andy
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.You can also use the following construct: