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)

1
  • 1
    System.out.println(array[0].length); Commented Sep 19, 2012 at 21:04

5 Answers 5

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for hinting that not all multi-dimensional arrays are necessarily square.
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.

Comments

1

array[0].length would give you 5

Comments

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

9 Comments

This will cause an IndexOutOfBounds exception.
Except that this will give you an ArrayIndexOutOfBoundsException since a is the length of array. You probably just meant to use 0
@Brian fixxed it - it's too late for me -.-
@user28061 Sure it would (and does). You can make 0-length arrays, and that's exactly what new boolean[0][5] does.
@A. R. S. If new boolean[0] works, array [0] is out of bounds.
|
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 

......

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.