user2541163
user2541163

Reputation: 737

Getting the size of a Multidimensional Array

Im currently stuck trying to get the size of the elements. It works if it in 2d

          String[][] = new String[5][10];  

          System.out.println(test[1].length);

However lets say i have this

          String[][][] = new String[5][10][15];
          System.out.println(test[2].length);

The above would not work. Is there anyway to get the size of the 3rd element which is 15? Edited. Thanks for your answers.

Upvotes: 0

Views: 72

Answers (3)

Fedor Skrynnikov
Fedor Skrynnikov

Reputation: 5609

each multidimensional array is simple an array where each element contain an array.

so in case of 3 dimensional array each element has 2 dimensional array inside. and each element of it has 1 dimensional array inside. So you need to do:

 String[][][] array = new String[5][10][15];
 int length = array[0][0].length;

So saying test[2] like in your code we are referring the 2 dimensional array which is on the third position and has a size [10][15]

Upvotes: 3

MadProgrammer
MadProgrammer

Reputation: 347194

I imagine you would need something like test[0][0].length

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83527

Since your example is a 3D array, you want the length of the "second dimension":

System.out.println(test2[0][0].length);

Upvotes: 5

Related Questions