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

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


答案 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 数组支持某些数据,请为包装类中的固定值提供 getter。


答案 2

2D 数组不是矩形网格。或者也许更好的是,Java中没有2D数组这样的东西。

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