Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is f(Double x) a better match than f(double... x)? [duplicate]

Tags:

java

Today I was studying for an incoming Java exam and I ran into this question:

Let A be a class defined as follows:

class A {
    public void f(Double x) { System.out.println("A.f(Double)"); }
    public void f(double... x) { System.out.println("A.f(double...)"); }
}

What is the output produced by the instruction A a = new A(); a.f(1.0);?

The answer seems to be A.f(Double) but I can't understand why. Could someone give me a proper explanation?

like image 692
faku Avatar asked Jan 14 '17 17:01

faku


1 Answers

Overload resolution always favours a function with an explicit number of arguments over a function with a variable argument list, even if that means that 1.0 is auto-boxed.

In a little more detail, a function is chosen with this precedence according to JLS 15.12.2:

  1. Type widening
  2. Auto-boxing
  3. Variable arguments
like image 153
Bathsheba Avatar answered Nov 03 '22 02:11

Bathsheba