174

I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:

public class MyClass {

 public static void main(String args[])
    {
  int[][] test; 
  test = new int[5][10];

  int row = test.length;
  int col = test[0].length;

  System.out.println(row);
  System.out.println(col);
    }
}

This prints out 5, 10 as expected.

Now take a look at this line:

  int col = test[0].length;

Notice that I actually have to reference a particular row, in order to get the column length. To me, this seems incredibly ugly. Additionally, if the array was defined as:

test = new int[0][10];

Then the code would fail when trying to get the length. Is there a different (more intelligent) way to do this?

1

13 Answers 13

241

Consider

public static void main(String[] args) {

    int[][] foo = new int[][] {
        new int[] { 1, 2, 3 },
        new int[] { 1, 2, 3, 4},
    };

    System.out.println(foo.length); //2
    System.out.println(foo[0].length); //3
    System.out.println(foo[1].length); //4
}

Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.

Sign up to request clarification or add additional context in comments.

8 Comments

Unrelated question about your answer. What is the technique/method called where you put "{...};" after the object definition. As a new developer I keep seeing this more and more.
Well, I understand that much :). I just thought there might be a specific name for the technique.
Not sure what the name of it is - object initialization? inline initialization? one of our Java Gurus will know
Per JLS 10.6 and 15.10, the curly braces part is simply an Array Initializer, while the whole thing starting with new is an Array Creation Expression.
Also, if you accept a 2D array as input, e.g. in a constructor. You should check it and throw exceptions where applicable.
|
27

A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.

import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    int[][] test; 
    test = new int[5][];//'2D array'
    for (int i=0;i<test.length;i++)
      test[i] = new int[i];

    System.out.println(Arrays.deepToString(test));

    Object[] test2; 
    test2 = new Object[5];//array of objects
    for (int i=0;i<test2.length;i++)
      test2[i] = new int[i];//array is a object too

    System.out.println(Arrays.deepToString(test2));
  }
}

Outputs

[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]

The arrays test and test2 are (more or less) the same.

Comments

21

It was really hard to remember that

    int numberOfColumns = arr.length;
    int numberOfRows = arr[0].length;

Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:

    int[][] arr = { {1, 1, 1, 1}, 
            
                    {2, 2, 2, 2}, 
                    
                    {3, 3, 3, 3} };

arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of rows. To get the number of columns, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of columns = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of columns by accessing the first array then its length. The other one (arr.length) is for the rows.

(Rows and columns corrected as per Evan's comment).

2 Comments

You have this backwards. "In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4." Actually, that means there are 4 columns.
Correct @Evan Rosica
5

Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:

if (row > 0) col = test[0].length;

Comments

5

If you have this array:

String [][] example = {{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"},
                       {"Why?", "Where?", "When?", "Who?"}, {"Yes!"}};

You can do this:

This gives you the number of rows:

example.length; = 4

Each row can be a different length, this gives you the number of columns:

example[0].length; = 2

example[1].length; = 3

example[2].length; = 4

example[3].length; = 1

Typing something like this will give you the length of the String inside the specific cell:

example[1][1].length(); = 3 //this cell has the word "Hey" which is 3 long.

Comments

3

There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.

You could easy create your own class to abstract the functionality you need.

If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.

Comments

2

.length = number of rows / column length

[0].length = number of columns / row length

1 Comment

Welcome to SO. You should add some more explanation to your answer.
1

Example Array 1:

int arr[][] = { { 1, 3, 1, 5 },
                 { 2, 2, 4, 1 },
                 { 5, 0, 2, 3 },
                 { 0, 6, 1, 2 } };

Example Array 2:

int arr[][] = { { 1, 3, 1 },
                 { 2, 2, 4 },
                 { 5, 0, 2 },
                 { 0, 6, 1 } };

Below function will work for any Symmetric and Asymmetric Array Matrix


 row_Count = arr.length
 column_Count = arr[0].length

Comments

0

Try this following program for 2d array in java:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

Comments

0
import java.util.Arrays;

public class Main {

    public static void main(String[] args) 
    {

        double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};

        int [][] removeRow = { {0}, {1}, {3}, {4}, };

        double[][] newTest = new double[test.length - removeRow.length][test[0].length];

        for (int i = 0, j = 0, k = 0; i < test.length; i++) {
            if (j < removeRow.length) {
                if (i == removeRow[j][0]) {
                    j++;
                    continue;
                }
            }
            newTest[k][0] = test[i][0];
            k++;
        }

        System.out.println(Arrays.deepToString(newTest));   
    }
}

1 Comment

Will print [[300.0], [600.0], [700.0], [800.0], [900.0], [1000.0]] convert to ints to lose decimal point. This solution assumes your input array will always be of size ([x][1])
0

With Java 8, allow you doing something more elegant like this:

int[][] foo = new int[][] {
        new int[] { 1, 2, 3 },
        new int[] { 1, 2, 3, 4},
    };

int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length

Comments

0
int rows=arr.length; //For knowing No of rows

int cols=arr[0].length; //For Knowing No of columns

Run This code... and Understand...

public class Store2darrays {   

    public static void main(String args[]) {
      int[]arr={1,2,3,4};
      System.out.println(arr.length);
      int[][] arr2d={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
      System.out.println(arr2d.length);
      System.out.println(arr2d);
      System.out.println(arr2d[0]);
      System.out.println(arr2d[1]);
      System.out.println(arr2d.length);
      System.out.println(arr2d[0].length); }
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-2
public class Array_2D {
int arr[][];
public Array_2D() {
    Random r=new Random(10);
     arr = new int[5][10];
     for(int i=0;i<5;i++)
     {
         for(int j=0;j<10;j++)
         {
             arr[i][j]=(int)r.nextInt(10);
         }
     }
 }
  public void display()
  {
         for(int i=0;i<5;i++)

         {
             for(int j=0;j<10;j++)
             {
                 System.out.print(arr[i][j]+" "); 
             }
             System.out.println("");
         }
   }
     public static void main(String[] args) {
     Array_2D s=new Array_2D();
     s.display();
   }  
  }

1 Comment

this is not related to the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.