2
class test {
    public static void m1(int...x,double...y) {
        /* some code here */
    }  

     public static void main(String args[]){
         m1();
         m1(10,20,3.5);
         m1(20,2.5,3.5,4.5);
     }
}

Whenever we use a method, it takes only one variable, mostly at end of the method signature. Why does this happen?

Why we can't use more than one variable length argument? I am looking for the answer from the compiler's point of view.

Roman C
  • 49,761
  • 33
  • 66
  • 176
anirban karak
  • 732
  • 7
  • 20
  • 2
    How would you tell the two lists apart? – Hot Licks Oct 04 '13 at 19:13
  • Yes, you can't use more than one variable length parameter and it should always be the last one on the list. – PM 77-1 Oct 04 '13 at 19:13
  • Where does the first vararg end and where does the second one begin? You can't tell apart the two list without further information. In those cases, two arrays are your best bet. – Fritz Oct 04 '13 at 19:15
  • So the second `m1` call should pass one `int` and two `double` parameters, right? With the `20` automatically being converted from an integer to a `double`. – ajb Oct 04 '13 at 19:27

4 Answers4

3

What if the two variable types were the same:

public static void m1(int...x, int...y) {

Where should the compiler split the input arguments between x and y? I don't know either. The compiler must disallow this, because there is no good way to handle it.

The variable arity ("varargs") parameter must be at the end of the method signature, so that the compiler can tell which arguments map to which formal parameters. Any arguments beyond the fixed parameters gets sent to an array that represents the varargs parameter.

The JLS, Section 8.4.1, says:

The last formal parameter of a method or constructor is special: it may be a variable arity parameter, indicated by an ellipsis following the type.

It is enforced in the JLS and the compiler for those reasons above.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

In short answer is , no you can't use more than one variable signature.

Prashant Chikhalkar
  • 511
  • 1
  • 8
  • 19
  • 1
    Isn't the question, *why*? OP already knows that its not allowed and that it must be present as the last parameter. – Rahul Oct 04 '13 at 19:20
1

I mean, there's no reason why the compiler couldn't do that as long as the types of the parameter types around the variadic parameters are different. After all, it is essentially just syntactic sugar for putting the arguments into arrays.

But from a language design standpoint, it may just cause more confusion/problems than its worth.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
0

varargs should be used only at the end of the method parameter. You can't have two varargs.

The compiler can't match argument and parameter with commas alone..

Alfa
  • 599
  • 6
  • 22