在 Java 中获取 2D 数组的数组长度
2022-08-31 07:14:41
我需要获取行和列的2D数组的长度。我已成功完成此操作,使用以下代码:
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。
现在看看这行:
int col = test[0].length;
请注意,我实际上必须引用特定的行才能获得列长度。对我来说,这似乎非常丑陋。此外,如果数组定义为:
test = new int[0][10];
然后,当尝试获取长度时,代码将失败。有没有一种不同的(更智能的)方法来做到这一点?