Getting the array length of a 2D array in Java

前端 未结 12 2319
耶瑟儿~
耶瑟儿~ 2020-11-27 09:27

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 s         


        
12条回答
  •  清歌不尽
    2020-11-27 09:50

    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 columns. To get the number of rows, 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 rows = 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 rows by accessing the first array then its length. The other one (arr.length) is for the columns.

提交回复
热议问题