簡體   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