Multidimensional Arrays lengths in Java

后端 未结 8 1090
一个人的身影
一个人的身影 2020-12-04 18:15

How to find the lengths of a multidimensional array with non equal indices?

For example, I have int[][] pathList = new int[6][4]

Without actuall

8条回答
  •  情歌与酒
    2020-12-04 19:09

    In Java we can't use Length field like we used to one-dimensional arrays. So simply writing a few lines of code solves this problem. First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array

    int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};

    the result of System.out.println(numbers.length); is 2, because you have 2 rows. So, you should use this to solve this problem. Example:

    public class Main {
    
    public static void main(String[] args) {
    
        //Array definition
        int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
    
        //Number of array's elements
        int result = 0;
    
        //calculate via loop
        for(int i=0; i< numbers.length; i++){
            result +=  numbers[i].length;
        }
    
        //output
        System.out.println(result);
    }
    

    }

提交回复
热议问题