我正在尝试构建一个遍历嵌套数组的静态方法。我想将此方法参数设置为接受任意数量的嵌套数组。换句话说,此函数应该能够操作数组或数组数组的数组(例如(。
我在这里举了一个例子:
private static void doStuffWithArrays(someType arrays){
//Do some stuff
}
什么是正确的数据类型来代替someType
?
您应该使用Object[]
。
JDK中采用任意嵌套数组的方法(如deepToString
(也可以这样做。
由于您不知道最外层数组中的对象是否为内部数组,因此必须检查getClass().isArray()
:
private static void doStuffWithArrays(Object[] outermostArray){
for (int i = 0 ; i < outermostArray.length ; i++) {
Object outerElement = outermostArray[i];
if (outerElement.getClass().isArray()) {
Object[] innerArray = (Object[])outermostArray[i];
// ... do things with innerArray
} else {
// we reached the innermost level, there are no inner arrays
}
}
}
但是,如果处理的是基元数组,则需要分别检查每个基元数组类,然后转换为正确的基元数组。
if (outerElement.getClass() == int[].class) {
int[] innerArray = (int[])outermostArray[i];
// ... do things with innerArray
} else if (outerElement.getClass() == short[].class) {
short[] innerArray = (short[])outermostArray[i];
// ... do things with innerArray
} else if (outerElement.getClass() == long[].class) {
long[] innerArray = (long[])outermostArray[i];
// ... do things with innerArray
} else if ... // do this for all the other primitive array types
} else if (outerElement.getClass().isArray()) {
Object[] innerArray = (Object[])outermostArray[i];
// ... do things with innerArray
} else {
// we reached the innermost level, there are no inner arrays
}
deepToString
也这样做。