Getting the array length of a 2D array in Java

前端 未结 12 2298
耶瑟儿~
耶瑟儿~ 2020-11-27 09:27

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         


        
12条回答
  •  时光取名叫无心
    2020-11-27 09:46

    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

提交回复
热议问题