开发者社区> 问答> 正文

在Java中获取2D数组的数组长度

我需要获取行和列的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]; 然后,当尝试获取长度时,代码将失败。是否有其他方法(更智能)来做到这一点? 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 10:11:08 457 0
1 条回答
写回答
取消 提交回答
  • 考虑

    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数组支持某些数据,请在包装器类中为固定值提供吸气剂。

    2020-02-08 10:11:20
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载