首页 > 解决方案 > 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?

标签: java

解决方案


You should use Object[].

Methods in the JDK that takes an arbitrarily nested array, like deepToString, do this too.

Since you don't know whether an object in that outermost array is an inner array, you would have to check 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.


推荐阅读