Get the size of a 2D array

JavaArraysMultidimensional Array

Java Problem Overview


Okay, so I have a 2D array z[50][50] and z's size is therefore 50 * 50, but if I say z.length I only get 50 back. How do I get the real size of a 2D array?

Java Solutions


Solution 1 - Java

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

Solution 2 - Java

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliamView Question on Stackoverflow
Solution 1 - JavaMark ElliotView Answer on Stackoverflow
Solution 2 - JavaPatrick TylerView Answer on Stackoverflow