Overloading and Ambiguity in Varargs in Java

Java provides the facility of overloading methods which means to have methods with the same name but with different function signatures. One can overload the varargs arguments) in a number of ways. But sometimes this leads to ambiguity. To write a function using vararg three periods(…) are used.  The basic function prototype is:

function_return_type name(data_type … v)

For example:

int max(int ... v)
{
    //function body
}

Overloading varargs in Java

class varargs
{
  static void func(int ... v)
  {
    System.out.print(v.length+" arguments\n");
    for(int x:v)
      System.out.print(x+" ");
  }
  static void func(boolean ...v)
  {
    System.out.print("\n"+v.length+ " arguments\n");
    for(boolean x:v)
      System.out.print(x+" ");
  }
  static void func(String msg, int ... v)
  {
    System.out.print("\n"+v.length+ " arguments\n"+msg+" ");
    for(int x:v)
      System.out.print(x+ " ");
  }
  public static void main(String args[])
  {
    func(1,2,3); 
    func(true , false , true);
    func("Hello world",1,2,3);
  }

}

Output:

3 arguments
1 2 3
3 arguments
true false true
3 arguments
Hello world 1 2 3

Ambiguity in varargs in Java

Often, at times overloading varargs becomes ambiguous. It means that when the function is invoked, the program does not know which function is being referred to. To better understand this, consider another version of the previous code.

class varargs
{
  static void func(int ... v)
  {
    System.out.print(v.length+" arguments\n");
    for(int x:v)
      System.out.print(x+" ");
  }
  static void func(boolean ...v)
  {
    System.out.print("\n"+v.length+ " arguments\n");
    for(boolean x:v)
      System.out.print(x+" ");
  }
  public static void main(String args[])
  {
    func(1,2,3); //fine
    func(true , false , true);  //fine
    func(); //will yield an error	
  }

}

Output:

varargs.java:19: error: reference to func is ambiguous
func(); //not fine
^
both method func(int...) in varargs and method func(boolean...) in varargs match
1 error

In the above code snippet, the overloading of func() is correct. However the code will not compile due to ambiguity. This is because the third call is valid for both the function signatures.

Leave a Reply

Your email address will not be published. Required fields are marked *