3
public static void main(String[] a){
          VarArgs obj = new VarArgs();
          obj.add(1,2);
}

class VarArgs{
       int add(int size, Integer... params){
       }
}

This code works. But I thought it will give ambiguity error. Because of type casting.

How does it work?

Gibbs
  • 21,904
  • 13
  • 74
  • 138

1 Answers1

6

The reference to call ambiguous error happens when there are two methods that are equally applicable; and in fact, one common way to fix that error is to remove one of the two methods. (See Compiler error : reference to call ambiguous.)

In your case, there's only one method to begin with, so there's no ambiguity: the 2 simply gets autoboxed into Integer.valueOf(2), then into new Integer[] { Integer.valueOf(2) }.

Community
  • 1
  • 1
ruakh
  • 175,680
  • 26
  • 273
  • 307