如何询问二维 Java 数组的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1698823/
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
How to ask 2-dimensional Java array for its number of rows?
提问by blahshaw
How should I go about asking a 2-dimensional array how many rows it has?
我应该如何询问二维数组有多少行?
回答by cletus
Firstly, Java technically doesn't have 2-dimensional arrays: it has arrays of arrays. So in Java you can do this:
首先,Java 在技术上没有二维数组:它有数组的数组。所以在 Java 中你可以这样做:
String arr[][] = new String[] {
new String[3],
new String[4],
new String[5]
};
The point I want to get across is the above is not rectangular (as a true 2D array would be).
我想说明的一点是上面不是矩形(就像真正的二维数组一样)。
So, your array of arrays, is it by columns then rows or rows then columns? If it is rows then columns then it's easy:
那么,您的数组数组是按列然后按行还是按行然后按列?如果是行然后是列,那么很容易:
int rows = arr.length;
(from the above example).
(来自上面的例子)。
If your array is columns then rows then you've got a problem. You can do this:
如果您的数组是列然后是行,那么您就遇到了问题。你可以这样做:
int rows = arr[0].length;
but this could fail for a number of reasons:
但这可能会因多种原因而失败:
- The array must be size 0 in which case you will get an exception; and
- You are assuming the length of the first array element is the number of rows. This is not necessarily correct as the example above shows.
- 数组的大小必须为 0,在这种情况下,您将收到异常;和
- 您假设第一个数组元素的长度是行数。如上例所示,这不一定正确。
Arrays are a crude tool. If you want a true 2D object I strongly suggest you find or write a class that behaves in the correct way.
数组是一个粗略的工具。如果您想要一个真正的 2D 对象,我强烈建议您找到或编写一个行为正确的类。
回答by camickr
Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
回答by Jé Queue
int[][] ia = new int[5][6];
System.out.println(ia.length);
System.out.println(ia[0].length);
回答by Stephen C
It depends what you mean by "how many rows".
这取决于您所说的“多少行”是什么意思。
For a start, a 2-dimensional array is actually a 1-D array of 1-D arrays in Java. And there is no requirement that a 2-D array is actually rectangular, or even that all elements in the first dimension are populated.
首先,二维数组实际上是 Java 中一维数组的一维数组。并且不需要二维数组实际上是矩形,甚至不需要填充第一维中的所有元素。
If you want to find the number of elements in the first dimension, the answer is simply
array.length
.If you want to find the number of elements in the second dimension of a rectangular 2-D array, the answer is `array[0].length.
If you want to find the number of elements in the second dimension of a non-rectangular or sparse 2-D array, the answer is undefined.
如果你想求第一维的元素个数,答案很简单
array.length
。如果你想在一个矩形二维数组的第二维中找到元素的数量,答案是`array[0].length。
如果要查找非矩形或稀疏二维数组的第二维中的元素数,答案是未定义的。