13

How should I go about asking a 2-dimensional array how many rows it has?

4 Answers 4

16

Firstly, Java technically doesn't have 2-dimensional arrays: it has arrays of arrays. So in Java you can do this:

String arr[][] = new String[] {
  new String[3],
  new String[4],
  new String[5]
};

The point I want to get across is the above is not rectangular (as a true 2D array would be).

So, your array of arrays, is it by columns then rows or rows then columns? If it is rows then columns then it's easy:

int rows = arr.length;

(from the above example).

If your array is columns then rows then you've got a problem. You can do this:

int rows = arr[0].length;

but this could fail for a number of reasons:

  1. The array must be size 0 in which case you will get an exception; and
  2. You are assuming the length of the first array element is the number of rows. This is not necessarily correct as the example above shows.

Arrays are a crude tool. If you want a true 2D object I strongly suggest you find or write a class that behaves in the correct way.

Sign up to request clarification or add additional context in comments.

Comments

9
Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row

1 Comment

Shouldnt that simply be //number of columns ?
5
int[][] ia = new int[5][6];
System.out.println(ia.length);
System.out.println(ia[0].length);

Comments

1

It depends what you mean by "how many rows".

For a start, a 2-dimensional array is actually a 1-D array of 1-D arrays in Java. And there is no requirement that a 2-D array is actually rectangular, or even that all elements in the first dimension are populated.

  • If you want to find the number of elements in the first dimension, the answer is simply array.length.

  • If you want to find the number of elements in the second dimension of a rectangular 2-D array, the answer is `array[0].length.

  • If you want to find the number of elements in the second dimension of a non-rectangular or sparse 2-D array, the answer is undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.