2

Why is this declaration not considered ambiguous in compile time?

void f(int a) {
    System.out.println("int");
}
void f(int... a) {
    System.out.println("int...");
}

e.g.:

f(2);     // to one parameter both method should match (f(int) runs)
f(2,2);   // f(int...)
user1063963
  • 1,355
  • 6
  • 22
  • 34
  • 3
    I don't have time to find it right now, but I bet the answer is somewhere in [JLS section 15.12.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2). – T.J. Crowder Feb 11 '13 at 09:25
  • Well, if compiler can find the exact match for the invocation, it will go for that, and not for var-args or even boxing. – Rohit Jain Feb 11 '13 at 09:28

2 Answers2

3

I think behind the scence var-args declaration is actually converted into an array by the compiler. so the method with var-args as parameter will actually look like below:

void f(int[] a) {
    System.out.println("int...");
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • what if there exists a method like _void f(int[] a)_? – Juvanis Feb 11 '13 at 09:22
  • 1
    @Juvanis, then it won't compile. – svz Feb 11 '13 at 09:24
  • @Juvanis if you have a method with an array as param and another method witht the same name with var-args as param its a compiler error. ambiguous method – PermGenError Feb 11 '13 at 09:24
  • Yes, var-args will create an array from the parameters, however this doesn't explain that special use case when there is only one parameter and there is also an one parameter version of that method. Which case both method can accept that single parameter. – user1063963 Feb 11 '13 at 09:51
  • @user1063963 din't quite get what you meant, can you elaborate it more, may b with a test case example :) – PermGenError Feb 11 '13 at 10:01
  • @PremGenError I have the two method like in the question, if I call f with a single parameter, the `f(int a)` gets called. However the `f(int... a)` can also accept that single parameter, so I would expect this overload to be ambiguous, because to a single parameter call both method is eligible. – user1063963 Feb 11 '13 at 10:14
0
void f(int... a) {
System.out.println("int...");

}

The above method can accept one or more values and the method containing only one argument i.e.

void f(int a) {
System.out.println("int");

} can also accept one value.

Qadir Hussain
  • 1,263
  • 1
  • 10
  • 26