繁体   English   中英

检查数组是单维还是多维

[英]Check if array is single or multidimensional

我正在为我的班级编写一个班级,该班级将用作辅助班级。 但是,我不知道是否可以检查任何给定的数组是单维还是多维。 我目前所拥有的:

public class Grid {
    private Object[] board;

    public Grid( Object[] b ) {
        this.board = b;
    }
    public Grid( Object[][] b ) {
        this.board = b;
    }
}

但显然,这不适用于任何给定的数组。 我是否需要为数组类型制作单独的方法? (请记住,我们将至少使用二维数组(至少到目前为止)

如果这样做,那会是最好的吗? (例如):

public Object getValue( Object[] b, int index ) throws ArrayIndexOutOfBoundsException {
    if ( index >= b.length ) {
        throw new ArrayIndexOutOfBoundsException( "Index too high" );
    }
    return b[ index ];
}

public Object getValue( Object[][] b, int index1, int index2 ) throws ArrayIndexOutOfBoundsException {
    if ( index1 >= b.length ) {
        throw new ArrayIndexOutOfBoundsException( "Index1 too high" );
    } else if ( index2 >= b[ 0 ].length ) {
        throw new ArrayIndexOutOfBoundsException( "Index2 too high" );
    }
    return b[ index1 ][ index2 ];
}

因此,从本质上讲,我想知道是否可以通过简单地检查数组是否为多维并将其用作我的方法的基础来使上面的示例更容易。

多维数组只是其中每个项目均为数组的数组。 您可以通过以下方法检查数组中是否包含子数组:

if (b.getClass().getComponentType().isArray()) {
    ...
}

然后,您可以递归地进行操作。

public void check(Object[] b, int... indices) {
    if (b.getClass().getComponentType().isArray()) {
        //check sub-arrays
        int[] i2 = Arrays.copyOfRange(indices, 1, indices.length);
        check(b[0], i2);
    }
    if (indices[0] > b.length) 
        throw new ArrayIndexOutOfBoundsException("Out of Bounds");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM