Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising a multidimensional array in Java

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"; 
like image 403
burntsugar Avatar asked Jul 01 '09 02:07

burntsugar


2 Answers

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]]]" 

Useful articles

  • Java: Initializing a multidimensional array
  • Java: Matrices and Multidimensional Arrays
like image 105
aioobe Avatar answered Oct 02 '22 16:10

aioobe


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.

like image 36
jameshales Avatar answered Oct 02 '22 16:10

jameshales