Varargs and Ambiguity in Java


There may be some unexpected errors when overloading a method that accepts variable-length arguments. These errors are associated with ambiguity because it is possible to create an ambiguity call in an overloaded varargs method.

Example

Program
//Varargs, overloading, and ambiguity.
class VarArgs
{
 public void Test(int ...a)
 {
  System.out.println("Test(int ...a) : "+"Number of args: "+a.length+" Contents: ");
  for(int i:a)
   System.out.print(i+" ");
   System.out.println();
 }
 public void Test(boolean ...a)
 {
  System.out.println("Test(boolean ...a) : "+"Number of args: "+a.length+" Contents: ");
  for(boolean i:a)
   System.out.print(i+" ");
   System.out.println();
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
    VarArgs v1=new VarArgs();
    v1.Test(1,2,3); //OK
    v1.Test(true,false,true); //OK
    //v1.Test(); //Error: Ambiguous
  }
}


In this program, the overloading of Test () is perfectly correct. Test () If this method is called without any parameters, it will give an error at compile time.

Test(); //Error: Ambiguous

Because the vararg parameter can be empty, this call could be translated into a call to Test(int ...) or Test(boolean ...). Both are equally valid. Thus, the call is inherently ambiguous.

Here is another example of ambiguity. The following overloaded versions of Test() are inherently ambiguous even though one takes a normal parameter:

void Test(int ...a)
{
 //body
}
void Test(int a, int ...b)
{
 //body
}

Although the parameter lists of Test() differ, there is no way for the compiler to resolve the following call:

Test(1);

Does this translate into a call to Test(int ...), with one varargs argument, or into a call to Test(int, int ...) with no varargs arguments? There is no way for the compiler to answer this. Thus, the situation is ambiguous.

Because of the ambiguity error that simply appears, sometimes you need to preload the overloading and use only the names of two different methods. Also, in some cases, ambiguity errors reveal a conceptual error in your code, which you can solve with more solutions.