Getting the array length of a 2D array in Java

user432209 picture user432209 · Oct 22, 2010 · Viewed 530.9k times · Source

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?

Answer

NG. picture NG. · Oct 22, 2010

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.