Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable argument function ambiguity

   public static void main(String[] args) {
       System.out.println(fun(2,3,4));
     }
   static int fun(int a,int b,int c)
   {
     return 1;
   }
   static int fun(int ... a)
   {
     return 0;  
   }

Output: 1

Question: In the above case why does the function fun select the 1st function and not the second.On what basis is the selection done since there is no way to determine which fun the user actually wanted to call ?

like image 706
Emil Avatar asked Sep 27 '10 10:09

Emil


People also ask

How do you overcome ambiguity in Java?

The inclusion of generics gives rise to a new type of error that you must guard against ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading.

How do the overloading methods can be ambiguous?

Sometimes unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide onto which method to bind the method call.

What are variable arguments or Varargs?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }

How can overloading method be resolved?

The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done). As expected the output is 10.


2 Answers

Basically there's a preference for a specific call. Aside from anything else, this means it's possible to optimize for small numbers of arguments, avoiding creating an array pointlessly at execution time.

The JLS doesn't make this very clear, but it's in section 15.12.2.5, the part that talks about a fixed arity method being more specific than another method if certain conditions hold - and they do in this case. Basically it's more specific because there are more calls which would be valid for the varargs method, just as if there were the same number of parameters but the parameter types themselves were more general.

like image 200
Jon Skeet Avatar answered Sep 19 '22 02:09

Jon Skeet


Compiler always selects the precise method when these kind of ambiguities are encountered. In your scenario func with three arguments is more precise than the variable arguments one so that is called.

EDIT: Edited as per skeet's comment.

like image 44
Faisal Feroz Avatar answered Sep 18 '22 02:09

Faisal Feroz