【发布时间】: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 这就是我所说的多维数组的意思,抱歉。