Multidimensional Arrays lengths in Java

后端 未结 8 1058
一个人的身影
一个人的身影 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);
    }
    

    }

    0 讨论(0)
  • 2020-12-04 19:12

    3-D array length

    int[][][] a = new int[2][3][7];
    int length=0;
    for(int[][] i:a){
        for(int j[]:i){
            length+=j.length;
        }   
    }           
    System.out.println(length);
    
    0 讨论(0)
提交回复
热议问题