Finding array dimensions in Java

Given some object o, I need to find its dimension (for example: for int[x][y][z]dimension 3), I decided that any suitable method would be in the class of the object.

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

works, but its source refers to its own method, so I can only get the answer from the string, and not directly.

If anyone knows a better way to do this, it will be appreciated (although more for the sake of curiosity than necessity).

+4
source share
2 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
}

PM 77-1 , - , . Java , .

+8

,

Object[] oa = new Object[] {1, new Object[] {"a", new int[] {5, 6, 7}, "c"}, 3};

getComponentType . , ​​

static int maxDim(Object[] oa) {
    int maxDim = 0;
    for(Object o: oa) {
        if(o instanceof int[] || o instanceof long[] || o instanceof short[] ||
           o instanceof byte[] || o instanceof float[] ||
           o instanceof double[] || o instanceof boolean[]) {
            maxDim = Math.max(maxDim, 1);
        } else if(o instanceof Object[]) {
            maxDim = Math.max(maxDim, maxDim((Object[])o));
        }
    }
    return maxDim + 1;
}
0

All Articles