Getting the array length of a 2D array in Java Ask Question

Getting the array length of a 2D array in Java Ask Question

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);
    }
}

This prints out 5, 10 as expected.

Now take a look at this line:

  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?

ベストアンサー1

Consider

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
}

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.

おすすめ記事