Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Arrays lengths in Java

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'?

like image 769
Bryan Harrington Avatar asked May 11 '11 01:05

Bryan Harrington


People also ask

Can you get length of 2D array Java?

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.

Can 2D arrays have different lengths?

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.

How many dimensions can multidimensional arrays have?

More than Three Dimensions Although an array can have as many as 32 dimensions, it is rare to have more than three.

What is the maximum size of 2D array?

C++, Using 2D array (max size 100*26) - LeetCode Discuss.


1 Answers

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; } 
like image 97
no.good.at.coding Avatar answered Oct 07 '22 13:10

no.good.at.coding