views:

894

answers:

5

Looking for 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";
A: 

I think this page will provide some direction to you.

TheVillageIdiot
+5  A: 

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.

_jameshales
Ooh, did not know that! Oops.
John Kugelman
+3  A: 

You can declare multi dimensional arrays like :

// 4 x 5 String arrays, all Strings are null
// [0] -> [null,null,null,null,null]
// [1] -> [null,null,null,null,null]
// [2] -> [null,null,null,null,null]
// [3] -> [null,null,null,null,null]

String[][] sa1 = new String[4][5];
for( int i = 0; i < sa1.length; i++ ) {           // sa1.length == 4
  for ( int j = 0; j < sa1[i].length; j++ ) {     //sa1[i].length == 5
    sa1[i][j] = "new String value";
  }
}


// 5 x 0  All String arrays are null
// [null]
// [null]
// [null]
// [null]
// [null]
String[][] sa2 = new String[5][];
for( int i = 0; i < sa2.length; i++ ) {
  String[] anon = new String[ /* your number here ];
  // or String[] anon = new String[]{"I'm", "a", "new", "array"};
  sa2[i] = anon;
}

// [0] -> ["I'm","in","the", "0th", "array"]
// [1] -> ["I'm", "in", "another"]
String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};
Clint
A: 

Not an answer to the exact question but a suggestion of alternative to multidimensional array: Multimap from Google Collections

Alex N.
+2  A: 

You can also use the following construct:

   String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                                { "X1", "Y1"},
                                                { "X2", "Y2"},
                                                { "X3", "Y3"},
                                                { "X4", "Y4"} };
A_M