Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the dimensionality of an array in Java

Given some object o, I need to find its dimensionality (eg: for int[x][y][z] the dimensionality is 3), I figured that any appropriate method would be in the class of the object.

int dimensionality = o.getClass().getName().indexOf('L');

works, but its source refers to a native method, so I'm left getting the answer from a string, rather than directly.

If anyone knows a better way of doing this it would be appreciated (although more for the sake of curiosity than necessity).

like image 950
user1837841 Avatar asked Jan 12 '23 13:01

user1837841


1 Answers

Here's a recursive solution using Class.isArray:

static int getDimensionality(final Class<?> type) {
    if (type.isArray()) {
        return 1 + getDimensionality(type.getComponentType());
    }
    return 0;
}

public static void main (String[] args) {
    System.out.println(getDimensionality(int.class));       // 0
    System.out.println(getDimensionality(int[].class));     // 1
    System.out.println(getDimensionality(int[][].class));   // 2
    System.out.println(getDimensionality(int[][][].class)); // 3
}

Although as PM 77-1 points out, this is not truly a measure of dimensionality but of the depth of a jagged array in terms of its static type. There are no true multidimensional arrays in Java, just arrays of arrays.

like image 148
Paul Bellora Avatar answered Jan 21 '23 08:01

Paul Bellora