How should I go about asking a 2-dimensional array how many rows it has?
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
Use len(arr) to find the number of row from 2d array. To find the number columns use len(arr[0]). Now total number of elements is rows * columns.
The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
If a 2D array does not have a fixed column size i.e., each array contained in the array of arrays is of variable length, we can still use arr. length to get the number of rows. However, to get the number of columns, you will have to specify which row you want to get the column length for: arr[rowNumber]. length .
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.
Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With