Is it possible in Java to find the number of dimensions of an array with an \'a priori\' unknown number of dimensions? That is, if one doesn\'t know the number of dimensions
The initial problem here is that you can't begin by saying something to the effect of:
int getNumDimensions(int[] array) { ... }
Because this would fail if theArray was actually an int[][], int[][][], etc. But all arrays in Java are Object subclasses, so this can work for any number of dimensions:
int getNumDimensions(Object array) {zz
if (array instanceof Object[]) {
// array has at least 2 dimensions (e.g. int[][])
return getNumDimensions(((Object[]) array)[0]) + 1;
}
if (array.getClass().isArray()) {
// array is, by process of elimination, one-dimensional
return 1;
}
return 0;
}
Edit: I've tried my hand at a non-recursive solution for those crazy million-dimensional arrays!
int getNumDimensions(Object array) {
Object tmp = array;
int nDimensions = 0;
while (True) {
if (array instanceof Object[]) {
// tmp has at least 2 dimensions (e.g. int[][])
tmp = ((Object[]) array)[0];
}
else if (tmp.getClass().isArray()) {
// tmp is, by process of elimination, one-dimensional
return nDimensions + 1;
}
nDimensions++;
}
}