Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!