1

I was trying to figure out the ins-and-outs of varargs and wrote the following code

public class VarArgTest {

/**
 * @param args
 */
public static void main(String[] args) {
    VarArgTest v = new VarArgTest();
    //Code 1
    System.out.println("haha");
}

public void m1(Integer a, Integer... ints) {
    System.out.println("1");
}

public void m1(Integer... ints) {
    System.out.println("2");
}
}

Now if I replace Code 1 by

v.m1(new Integer(1), new Integer(2));

I get the following message

The method m1(Integer, Integer[]) is ambiguous for the type VarArgTest

My question is, why throw the error at client code? Should it not be caught by compiler while defining the two m1 methods?

Chetter Hummin
  • 6,687
  • 8
  • 32
  • 44

2 Answers2

4

It's not an error in the overloads because there are still unambiguous invocations of those two methods.

v.m1(new Integer[] {1, 2})

and

v.m1(1, new Integer[] {2})

would both work just fine. It only becomes ambiguous when the compiler has to figure out how to turn the arguments in the invocation into arrays.

gk5885
  • 3,742
  • 21
  • 16
0

That means that those two methods cannot be distinguished when you would call

 v.m1(1,2,3,4) 

compilator does not know which method should be used.

You need to have different parameters (method signatures) when you overload.

e.g. this would be ok for compilator :

   public void m1(String a, Integer... ints) {
    System.out.println("1");
   }

   public void m1(Integer... ints) {
    System.out.println("2");
   }
Martin V.
  • 3,560
  • 6
  • 31
  • 47