Okay, so I ha开发者_如何学JAVAve 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?
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).
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
精彩评论