Finding length of all arrays multidimensional array, Java
Asked Answered
H

5

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)

Hindermost answered 19/9, 2012 at 21:3 Comment(1)
System.out.println(array[0].length);Achates
D
11

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

Divorcement answered 19/9, 2012 at 21:5 Comment(1)
+1 for hinting that not all multi-dimensional arrays are necessarily square.Piece
D
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.

Desmoid answered 19/9, 2012 at 21:57 Comment(0)
M
1

array[0].length would give you 5

Mudpack answered 19/9, 2012 at 21:6 Comment(0)
I
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

Inhabited answered 19/9, 2012 at 21:6 Comment(9)
This will cause an IndexOutOfBounds exception.Divorcement
Except that this will give you an ArrayIndexOutOfBoundsException since a is the length of array. You probably just meant to use 0Piece
@Piece fixxed it - it's too late for me -.-Inhabited
Well, I +1'd because of your bounds check with a > 0, but Idk who downvoted, sorry.Piece
@Piece I am not even sure if it is necessary, because new boolean[0][5] wouldn't work anyway, right?Inhabited
@Inhabited Sure it would (and does). You can make 0-length arrays, and that's exactly what new boolean[0][5] does.Piece
Why use array[a - 1].length when you could use array[0].length?Divorcement
@A. R. S. If new boolean[0] works, array [0] is out of bounds.Inhabited
Yes I understand, but you could just do if (array.length > 0) { int b = array[0].length; } instead of defining that a variable right?Divorcement
U
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 

......

Undertow answered 12/11, 2016 at 22:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.