Total amount of elements in two dimensional array

java, java-7

Solution

No there is no native Java functionality for this, as an array of arrays (of arrays (of arrays ...)) is not a language construct per se. Array is, but an array of arrays is just an array of Objects (which again may, but need not be arrays). The notation `Object[][]` just provides type-safety for multi-dimensional arrays.

There is no way you can calculate this without looping, but you can solve it using reflection and recursion for arrays of arbitrary dimensions.

A generic solution, where performance is not an issue, that counts all non-array elements for arbitrary dimensional arrays using recursion and `java.lang.reflect.Array` could look something like this:

public static int size(Object object) {
    if (!object.getClass().isArray()) {
        return 1;
    }

    int size = 0;
    for (int i = 0; i < Array.getLength(object); i++) {
        size += size(Array.get(object, i));
    }
    return size;
}

You can call this function with any object:

int[][] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};


Object[] array = {
    "1",
    new String[]{
        "2", "3", "4"
    },
    new int[][] {
        { 5 },
        { 6, 7 },
        { 8, 9, 10 }
    }
};


String literal = "literal";

System.out.println(size(matrix));
System.out.println(size(array));
System.out.println(size(literal));

would then output

9
10
1

It's not a very elegant solution, but as polygenelubricants puts it:

It's going to be very repetitive (but even `java.util.Arrays` is very repetitive), but that's the way it is in Java with arrays.

Problem

Recently we learned two dimensional arrays and solved task of calculating average of all elements in it. My code was like: ``` int a[][] = { {1, 2, 3, 4, 5}, {6, 4, 2, 7}, {3, 6}, {2, 6, 8}, }; int sum=0, amount=0; for (int[] row : a) for (int val : row) { sum += val; amount += 1; } return sum / (double) amount; ``` The thing is that I don't like the way I calculated the amount of elements in array. I tried to use size(), it not worked, tried to use Array and Arrays classes but both can retrieve neither amount of rows nor amount of elements in some row, just as a .length property. Question: is there any way of retrieving the amount of elements from two or more dimensional matrices without using loops?

Original source

Related problems