Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask 2-dimensional Java array for its number of rows?

Tags:

java

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

like image 418
blahshaw Avatar asked Nov 09 '09 02:11

blahshaw


People also ask

How do I count the number of rows in a 2D array in Java?

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.

How do I find the number of rows in an 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.

How do you find the total number of elements in a 2D array?

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.

How do you find the length of a 2D array column?

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 .


2 Answers

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.

like image 140
cletus Avatar answered Oct 06 '22 20:10

cletus


Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
like image 28
camickr Avatar answered Oct 06 '22 20:10

camickr