检查数组是单维还是多维

问题描述 投票:0回答:1

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

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

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

java arrays
1个回答
1
投票

多维数组只是一个数组,其中每个项都是数组。您可以通过以下方式检查数组中是否包含子数组:

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");
}
© www.soinside.com 2019 - 2024. All rights reserved.