Java 获取二维数组的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4111393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the size of a 2D array
提问by William
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?
好的,所以我有一个二维数组 z[50][50],因此 z 的大小是 50 * 50,但是如果我说 z.length,我只能得到 50。如何获得二维数组的实际大小?
采纳答案by Mark Elliot
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)
在 Java 中,二维数组实际上是长度可能不同的数组的数组(不能保证在二维数组中二维数组的长度都相同)
You can get the length of any 2nd dimension array as z[n].length
where 0 <= n < z.length
.
您可以获得任何二维数组的长度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).
如果您将 2D 数组视为矩阵,则可以简单地获取z.length
and z[0].length
,但请注意,您可能会假设第二维中的每个数组的长度相同(对于某些程序,这可能是合理的假设)。
回答by Patrick Tyler
Expanding on what Mark Elliotsaid 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:
扩展Mark Elliot之前所说的,假设数组数组中的每个数组的大小相同,获取 2D 数组大小的最简单方法是:
array.length * array[0].length