1

So basically from my searches on StackOverflow, this popped out (correct me if wrong):

  1. You can define function that accepts variable argument (in this case any Object) count this way:

    public void varadric(Object... arguments) {
        //I'm a dummy function
    }
    
  2. You call this method with any count of arguments (which extend Object) and you'll get one argument being Object[] in the function:

     public static main() {
         varadric("STRING", new ArrayList<int>());
     }
     public void varadric(Object... arguments) {
         System.out.println("I've received "+arguments.length+" arguments of any Object subclass type.");
     }
    
  3. You can instead somehow generate the input as Object[] array and pass as a single parameter without any change:

    public static main() {
        Object[] args = new Object[2];
        args[0] = "STRING";
        args[1] = new ArrayList<int>());
        //Should say it got 2 arguments again!
        varadric(args);
    }
    

Now my question is: Since Object[] implements Object too, does it mean it's not possible to pass it in varargs (ending up with nested array?)?

Imagine following scenario with more specific description:

 public void varadric(Object[]... arguments) {
      //I'm a function that expects array of arrays
      // - but I'm not sure if I'll allways get that
 }

Could someone make this clear for me?

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Try invoking `varadric((Object)args);` to see the different behavior. In that case, it will be considered as a single argument and wrapped within its own `Object[]`. That is, the variable `arguments` within the `varadric` method will be an `Object[]` containing an `Object[]` containing a `String` and an `ArrayList`. – Sotirios Delimanolis Mar 09 '15 at 19:24

2 Answers2

2

Well, there are a few options:

  • Create an array yourself:

    varadric(new Object[] { array })
    
  • Declare a local variable of type Object and get the compiler to wrap that in an array:

    Object tmp = array;
    varadric(tmp);
    
  • A variation on the above - just cast:

    varadric((Object) array);
    

But yes, you're right to say that when presented with a single argument of type Object[] and a varargs parameter declared as Object... foo, the compiler won't wrap it because it in an array, because it doesn't need to.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It will be a 2D array. This declaration public void varadric(Object[]... arguments) will receive an array (...) of Object[] Example:

public class Test {
    public static void main(String[] args) {
        Object[] o = new Object[2]; 
        o[1] = "hi";
        t(o);
    }

    public static void t(Object[]... arg) {
        System.out.println(arg[0][1]);
    }
}

will print: hi

ACV
  • 9,964
  • 5
  • 76
  • 81