如何询问二维Java数组的行数? [英] How to ask 2-dimensional Java array for its number of rows?
问题描述
我该如何询问二维数组它有多少行?
How should I go about asking a 2-dimensional array how many rows it has?
推荐答案
首先,Java技术上没有没有二维数组:它有数组数组。所以在Java中你可以这样做:
Firstly, Java technically doesn't have 2-dimensional arrays: it has arrays of arrays. So in Java you can do this:
String arr[][] = new String[] {
new String[3],
new String[4],
new String[5]
};
我想要的结果是上面不是矩形(因为真正的2D数组会是)。
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;
(来自上面的例子)。
如果您的数组是列然后行,那么您就遇到了问题。你可以这样做:
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:
- 数组必须为0,在这种情况下,您将获得异常;和
- 您假设第一个数组元素的长度是行数。这不一定正确,如上例所示。
数组是一个粗糙的工具。如果你想要一个真正的2D对象,我强烈建议你找到或写一个行为正确的类。
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.
这篇关于如何询问二维Java数组的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!