[英]Check if array is single or multidimensional
I'm writing a class for my class that I'm going to be using as a helper class. 我正在为我的班级编写一个班级,该班级将用作辅助班级。 However, I don't know if it's possible or not to check if any given array is single or multidimensional.
但是,我不知道是否可以检查任何给定的数组是单维还是多维。 What I currently have:
我目前所拥有的:
public class Grid {
private Object[] board;
public Grid( Object[] b ) {
this.board = b;
}
public Grid( Object[][] b ) {
this.board = b;
}
}
but obviously that wouldn't work for any given array. 但显然,这不适用于任何给定的数组。 Would I have to just make separate methods for the type of array?
我是否需要为数组类型制作单独的方法? (Keep in mind we won't be using more than two-dimension arrays (at least yet)
(请记住,我们将至少使用二维数组(至少到目前为止)
Would it be best if I did this? 如果这样做,那会是最好的吗? (for example):
(例如):
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 ];
}
So, in essence, I'm wondering if it's possible to make the above example easier by simply being able to check if an array is multidimensional or not, and use that as a basis of my methods. 因此,从本质上讲,我想知道是否可以通过简单地检查数组是否为多维并将其用作我的方法的基础来使上面的示例更容易。
A multidimensional array is simply an array where each of the items are arrays. 多维数组只是其中每个项目均为数组的数组。 You can check if an array has sub-arrays in it by:
您可以通过以下方法检查数组中是否包含子数组:
if (b.getClass().getComponentType().isArray()) {
...
}
Then you can do it recursively. 然后,您可以递归地进行操作。
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.