Reputation: 131
How should I go about asking a 2-dimensional array how many rows it has?
Upvotes: 13
Views: 44787
Reputation: 718788
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.
Upvotes: 1
Reputation: 10637
int[][] ia = new int[5][6];
System.out.println(ia.length);
System.out.println(ia[0].length);
Upvotes: 5
Reputation: 324118
Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
Upvotes: 9
Reputation: 625057
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:
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.
Upvotes: 16