2

Could anyone please explain why this code throws an ambiguous overload error, surely the Integer method is more specific and applicable?

Thanks,

Ned

package object_orientation;
public class Ambiguous {
    //ambiguous error compiler unsure whether boxing is needed or not
    static void overload(Integer... d){
        System.out.println("Integer");
    }

    static void overload(long... d){
        System.out.println("Long");
    }

    public static void main(String a[]){
        int i = 1;
        overload(i);
    }
}
William Morrison
  • 10,953
  • 2
  • 31
  • 48
Xivilai
  • 2,481
  • 3
  • 15
  • 15
  • 1
    see that `Integer` is different from `int`. `Integer` is a wrapper. – fpe Aug 19 '13 at 13:05
  • 1
    good post on this - http://stackoverflow.com/questions/2521293/bug-with-varargs-and-overloading – Zack Macomber Aug 19 '13 at 13:08
  • 1
    if you change `long...` to `long` in your overload method, it will compile. I believe varargs translate to being an array at compile time so I think that's where the ambiguity is happening – Zack Macomber Aug 19 '13 at 13:11

1 Answers1

3

These concepts in Java should help, Boxing + Widening is allowed, but not Widening + Boxing.

These rules of Widening, Boxing and Vararg should help:

  1. Primitive Widening > Boxing > Varargs.
  2. Widening and Boxing (WB) not allowed.
  3. Boxing and Widening (BW) allowed.
  4. While overloading, Widening + vararg and Boxing + vararg can only be used in a mutually exclusive manner
  5. Widening between wrapper classes not allowed.
  6. Widening+varArgs & Boxing+varargs are individually allowed (but not allowed in overloaded version of method).
  7. Boxing+Widening is preferred over Boxing+Varargs.

Hope this helps.

JNL
  • 4,683
  • 18
  • 29
  • Thanks. I thought the int would simply be boxed and applied to the Integer var-args and the long var-args ignored, because you can't widen and box at the same time. The compiler tells me I have an Ambiguous error of type Ambiguous – Xivilai Aug 19 '13 at 14:16