【问题标题】:Check if array is single or multidimensional检查数组是单维还是多维
【发布时间】:2018-06-01 04:24:46
【问题描述】:

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

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

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

【问题讨论】:

  • 你写了 "... 但显然这不适用于任何给定的数组..." - 为什么不呢?这对我来说并不明显。
  • b.getClass().getComponentType().isArray().
  • 这将有助于您的所有用例。 stackoverflow.com/questions/2512082/…
  • 记住,Java 不支持多维数组。例如。二维数组只是一个数组数组,其中所有嵌套数组都具有相同的长度。 Java array-of-arrays (x[][]) 实际上是 jagged 数组。
  • @Andreas 这就是我所说的多维数组的意思,抱歉。

标签: java arrays


【解决方案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");
}

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 2010-09-26
    • 2010-09-13
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多