I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:
public class MyClass {
public s
It is also possible to get the quantity of elements of a 2d-array row, using "Arrays.toString(arr[x])", or total quantity of elements of a 2d/3d-array, using "Arrays.deepToString(arr)". It will give out a string, consisting of all the elements of the array separated by commas (rows are also limited with square brackets). AND: the main idea is that the total quantity of commas will be by 1 less than the total number of array / array row elements! Then you create one more string consisting only of all the commas (removing everything else using a regex), and its length + 1 will be the result we need. Examples:
public static int getNumberOfElementsIn2DArray() {
int[][] arr = {
{1, 2, 3, 1, 452},
{2, 4, 5, 123, 1, 22},
{23, 45},
{1, 122, 33},
{99, 98, 97},
{6, 4, 1, 1, 2, 8, 9, 5}
};
String str0 = Arrays.deepToString(arr);
String str = str0.replaceAll("[^,]","");
return str.length() + 1;
}
It will return "27";
public static int getNumberOfElementsIn2DArrayRow() {
int[][] arr = {
{1, 2, 3, 1, 452},
{2, 4, 5, 123, 1, 22},
{23, 45},
{1, 122, 33},
{99, 98, 97},
{6, 4, 1, 1, 2, 8, 9, 5}
};
String str0 = Arrays.toString(arr[5]);
String str = str0.replaceAll("[^,]","");
return str.length() + 1;
}
It will return "8".
Note! This method will return a wrong result if your multidimensional array is a String- or char array, in which content of elements contains commas :D