简体   繁体   English

采用无限嵌套数组的方法的参数类型是什么?

[英]What is the argument's type for a method that takes indefinite nested arrays?

I am trying to build a static method that traverses a nested array of arrays.我正在尝试构建一个遍历嵌套数组数组的静态方法。 I would like to set this method argument to accept any number of nested arrays.我想将此方法参数设置为接受任意数量的嵌套数组。 In other words, this function should be able to operate an array of arrays or an array of array of arrays (for example).换句话说,这个函数应该能够操作一个数组数组或一个数组数组(例如)。

I illustrate here with an example:我在这里用一个例子来说明:

private static void doStuffWithArrays(someType arrays){
        //Do some stuff
    }

What is the right data type to be in place of someType ?代替someType的正确数据类型是什么?

You should use Object[] .您应该使用Object[]

Methods in the JDK that takes an arbitrarily nested array, like deepToString , do this too. JDK 中采用任意嵌套数组的方法(如deepToString )也执行此操作。

Since you don't know whether an object in that outermost array is an inner array, you would have to check getClass().isArray() :由于您不知道最外层数组中的对象是否是内部数组,因此您必须检查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 you are dealing with arrays of primitives, however, you would need to check each of the primitive array classes separately, then cast to the correct one.但是,如果您正在处理基元数组,则需要分别检查每个基元数组类,然后转换为正确的类。

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 does this too. deepToString也这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM