简体   繁体   中英

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

我该如何询问二维数组它有多少行?

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.

Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
int[][] ia = new int[5][6];
System.out.println(ia.length);
System.out.println(ia[0].length);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM