I have a 2D array of doubles in Java which is basically a table of values and I want to find out how many rows it has…
It is declared elsewhere (and allocated) like this:
double[][] table;
then passed to a function…
private void doSomething(double[][] table) { }
In my function I want to know the length of each dimension without having to pass them around as arguments. I can do this for the number of columns but don’t know how to do it for the rows…
int cols = table[0].length; int rows = ?;
How do I do that?
Can I just say…
int rows = table.length;
Why would that not give rows x cols?
In Java a 2D array is nothing more than an array of arrays.
This means that you can easily get the number of rows like this:
This also means that each row in such an array can have a different amount of elements (i.e. each row can have a varying number of columns).
This will only give you the number of columns in the first row, but the second row could have more or less columns than that.
You could specify that your method only takes rectangular arrays and assume that each row has the same number of columns than the first one. But in that case I’d wrap the 2D-array in some Matrix class (that you might have to write).
This kind of array is called a Jagged Array.