1

This code has ambiguous behaviour as per ob.fn() call which is quite clear as per the function definition. But when changed the function definition from 'boolean' to 'double' the behaviour was quite unexpected to me.

public class Varargs {
    public void fn(boolean ...a){
        System.out.println("calling double fn");
        for(boolean i:a){
            System.out.print(i+" ");
        }
        System.out.println("\n");
    }

    public void fn(int ...a){
        for(int i:a){
            System.out.print(i+" ");
        }
        System.out.println("\n");
    }



    public static void main(String[] args) {
        System.out.println("Entering 5 numbers.");
        Varargs ob = new Varargs();
        ob.fn();
        ob.fn(2,5,5,3,2,2,3,4,3,3);
    }

}

But why isn't the ambiguity being shown in this ?

public class Varargs {
    public void fn(double ...a){
        System.out.println("calling double fn");
        for(double i:a){
            System.out.print(i+" ");
        }
        System.out.println("\n");
    }

    public void fn(int ...a){
        for(int i:a){
            System.out.print(i+" ");
        }
        System.out.println("\n");
    }



    public static void main(String[] args) {
        System.out.println("Entering 5 numbers.");
        Varargs ob = new Varargs();
        ob.fn();
        ob.fn(2,5,5,3,2,2,3,4,3,3);
    }

}

After changing 'boolean' to 'double' , what led to disappearance of ambuigity?

dJOKER_dUMMY
  • 699
  • 2
  • 6
  • 5
  • Just to remind you, there are 3 rules exist to resolve ambiguity in method overloading; Stretching, Boxing, Varargs and these rules will be applied in the given order. Think about you have methods `gn(double a) and gn(int a)`. Here calling `obj.gn(5)`, `gn(int a)` function will be invoked but if you comment 'gn(int a)' function then 'gn(double a)' will be called due to stretching. In your case also `fn(int...)` is capable of holding so double function is not coming to picture. – sanit Dec 26 '17 at 09:46
  • But shouldn't that happen for fn(boolean ...a) too ? Shouldn't the call to fn(int ...a) be overlooked avoiding ambiguity? As boolean is also capable to handle the function call without the paramenter. – dJOKER_dUMMY Dec 26 '17 at 10:00
  • Incase of `gn(int) VS gn(double)` only if `gn(int)` in not capable then due to stretching rule `gn(double)` will be called. Stretching will be applied across numerical primitives like int, long, double etc, but not boolean. For example we can't write `boolean b = 5` but can write 'double a=5'. In `boolean vs int` stretching not applied and though both are capable of receiving the call, they are getting into ambiguity. – sanit Dec 26 '17 at 10:24
  • Also look into duplicate marked answer, surely you will get much better understanding. It contain codes and code explanations are always better than comment explanation. – sanit Dec 26 '17 at 10:27

0 Answers0