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’?
This will give you the length of the array at index
iIt’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
pathListis instantiated equal tonew int[6][], it can hold 6int []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
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: