在Java中获取二维数组的数组长度

新手上路,请多包涵

我需要获取行和列的二维数组的长度。我已经成功地做到了这一点,使用下面的代码:

 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];

然后代码在尝试获取长度时会失败。有没有不同的(更智能的)方法来做到这一点?

原文由 user432209 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 597
2 个回答

考虑

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
}

每行的列长度不同。如果您通过固定大小的二维数组支持某些数据,则在包装器类中为固定值提供 getter。

原文由 NG. 发布,翻译遵循 CC BY-SA 2.5 许可协议

二维数组不是矩形网格。或者更好的是,Java 中没有二维数组这样的东西。

 import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    int[][] test;
    test = new int[5][];//'2D array'
    for (int i=0;i<test.length;i++)
      test[i] = new int[i];

    System.out.println(Arrays.deepToString(test));

    Object[] test2;
    test2 = new Object[5];//array of objects
    for (int i=0;i<test2.length;i++)
      test2[i] = new int[i];//array is a object too

    System.out.println(Arrays.deepToString(test2));
  }
}

产出

[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]

阵列 testtest2 (或多或少)相同。

原文由 Ishtar 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题