Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of a 2D array [duplicate]

Okay, so I have a 2D array z[50][50] and z's size is therefore 50 * 50, but if I say z.length I only get 50 back. How do I get the real size of a 2D array?

like image 680
William Avatar asked Nov 06 '10 01:11

William


People also ask

How do you determine the size of a 2D array?

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. When calling the length of a column, we pinpoint the row before using . length .

How do you check for duplicates in a 2D array?

Turn the 2d array into a 1d array ( List<Integer> ), then loop through the 1d array counting the duplicates as you find them and removing them so you don't count them more than once.

How do you check if each element in a 2D array is unique?

Put all the numbers in a Set and just match the size of array and set. If both are equal then all your numbers in array are unique.

Can you clone a 2D array?

A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.


2 Answers

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

like image 160
Mark Elliot Avatar answered Oct 12 '22 17:10

Mark Elliot


Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length
like image 22
Patrick Tyler Avatar answered Oct 12 '22 18:10

Patrick Tyler