7

I would like to use a multidimensional array to store a grid of data. However, I have not found a simple way to find the length of the 2nd part of the array. For example:

boolean[][] array = new boolean[3][5];
System.out.println(array.length);

will only output 3.

Is there another simple command to find the length of the second array? (i.e. output 5 in the same manner)

Nelson
  • 49,283
  • 8
  • 68
  • 81
HedonicHedgehog
  • 592
  • 1
  • 6
  • 17

5 Answers5

11

Try using array[0].length, this will give the dimension you're looking for (since your array is not jagged).

arshajii
  • 127,459
  • 24
  • 238
  • 287
7
boolean[][] array = new boolean[3][5];

Creates an array of three arrays (5 booleans each). In Java multidimensional arrays are just arrays of arrays:

array.length

gives you the length of the "outer" array (3 in this case).

array[0].length

gives you the length of the first "inner" array (5 in this case).

array[1].length

and

array[2].length

will also give you 5, since in this case, all three "inner" arrays, array[0], array[1], and array[2] are all the same length.

trutheality
  • 23,114
  • 6
  • 54
  • 68
1

array[0].length would give you 5

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1
int a = array.length;

if (a > 0) {
  int b = array[a - 1].length;
}

should do the trick, in your case a would be 3, b 5

user28061
  • 354
  • 1
  • 4
  • 14
0

You want to get the length of the inner array in a 3 dimensional array

e.g.

int ia[][][] = new ia [4][3][5];
System.out.print(ia.length);//prints 4
System.out.print(ia[0].length);//prints 3
System.out.print(ia[0].[0].length); // prints 5 the inner          array in a three  D array

By induction: For a four dimensional array it's:

ia[0].[0].[0].length 

......