How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length
, but how to obtain the '4'?
Learn how to get the length of a 2D array in Java We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
You can also use an array initializer to declare, create and initialize a two-dimensional array. FIGURE 7.2 A two-dimensional array is a one-dimensional array in which each element is another one-dimensional array. Each row in a two-dimensional array is itself an array. Thus, the rows can have different lengths.
More than Three Dimensions Although an array can have as many as 32 dimensions, it is rare to have more than three.
C++, Using 2D array (max size 100*26) - LeetCode Discuss.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With