Trevor Arjeski
Trevor Arjeski

Reputation: 2168

Finding 2D array length?

I know that array.length returns the number of rows, but I'm looking for the length of each row. Apparently array[0].length doesnt do it. Any ideas?

Upvotes: 2

Views: 6741

Answers (2)

starblue
starblue

Reputation: 56832

In Java there are only one-dimensional arrays internally.

A two-dimensional array is an array of arrays, so the array for the first dimension and each of the arrays for the second dimension may have a different size.

Upvotes: 1

jcomeau_ictx
jcomeau_ictx

Reputation: 38492


jcomeau@intrepid:~/rentacoder$ cat /tmp/test.java 
public class test {
 public static void main(String[] args) {
  int[][] blah = {{1, 2}, {3, 4, 5}};
  System.out.println("lengths: " + blah.length + ", " + blah[0].length +
   ", " + blah[1].length);
 }
}
jcomeau@intrepid:~/rentacoder$ (cd /tmp && java test)
lengths: 2, 2, 3

Seems to work.

Upvotes: 4

Related Questions