Getting unknown number of dimensions from a multidimensional array in Java

前端 未结 5 1619
天命终不由人
天命终不由人 2020-12-18 05:23

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

5条回答
  •  青春惊慌失措
    2020-12-18 05:50

    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++;
        }
    }
    

提交回复
热议问题