Multidimensional Arrays lengths in Java

后端 未结 8 1076
一个人的身影
一个人的身影 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:02

    This will give you the length of the array at index i

    pathList[i].length
    

    It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.


    So when you create arrays the way you've shown in your question, you may as well do

     pathList[0].length
    

    since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:

    for(int i = 0; i < pathList.length; i++)
    {
        int currLen = pathList[i].length;
    }
    

提交回复
热议问题