1

Why is the below code giving compilation error "The method show(Object[]) is ambiguous for the type VarArgs"?.

Error in line show(10,20,30);

public class VarArgs {
    public static void main(String[] args) {
        show(10,20,30);
    }

    private static void show(Object... args){
        System.out.println("Object");
    }

    private static void show(int... arry){
        System.out.println("Integer");
    }
}

JDK : jdk1.6.0_23

Santhosh G
  • 21
  • 1
  • Thanks Tunaki. Not sure its a duplicate because there overloading is with int vararg with Integer vaarg. When show(10,20,30) is made, why there is a confusion?. On the other hand private static void show(Integer... arry) works.. – Santhosh G Sep 28 '16 at 12:39

1 Answers1

1

You should first read this and then pass an int array instead of 3 ints in show method.

What is happening here is Java compiler is automatically boxing int to Integer class and since Integer class is a subclass of Object class both versions of show() method could accept show(int[]) and hence compiler is throwing ambiguous error.

java_doctor_101
  • 3,287
  • 4
  • 46
  • 78
  • show(int[]) cannot take show(10,20,30). Also if i change the second method to private static void show(Integer... arry), it works. – Santhosh G Sep 28 '16 at 12:52
  • I think you misunderstood, by show(int[]) I mean calling show method with an int array as it's paramter. – java_doctor_101 Sep 28 '16 at 12:54
  • For a vararg, show(10,20,30) is an array passed, right?. What i think is, second method is boxed to Integer and then widened to Object. Not sure though. – Santhosh G Sep 28 '16 at 13:01