在Java中获取二维数组的数组长度 [英] Getting the array length of a 2D array in Java
问题描述
我需要获取行和列的二维数组的长度.我已经成功地做到了这一点,使用以下代码:
I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:
public class MyClass {
public static void main(String args[])
{
int[][] test;
test = new int[5][10];
int row = test.length;
int col = test[0].length;
System.out.println(row);
System.out.println(col);
}
}
这会按预期打印出 5、10.
This prints out 5, 10 as expected.
现在看看这一行:
int col = test[0].length;
请注意,我实际上必须引用特定行,才能获得列长度.对我来说,这看起来非常丑陋.此外,如果数组定义为:
Notice that I actually have to reference a particular row, in order to get the column length. To me, this seems incredibly ugly. Additionally, if the array was defined as:
test = new int[0][10];
然后代码在尝试获取长度时会失败.有没有其他(更智能)的方法来做到这一点?
Then the code would fail when trying to get the length. Is there a different (more intelligent) way to do this?
推荐答案
考虑
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
每行的列长度不同.如果您通过固定大小的 2D 数组支持某些数据,则为包装类中的固定值提供 getter.
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
这篇关于在Java中获取二维数组的数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!