Method overloading with variable argument

I think that would be a stupid question, but I cannot understand why this is so.

the code

public class OverloadingTest {
    public static int sum(int ...a){
        int sum=0;
        for(int i : a){
            sum += i;
        }
        System.out.print("this is variant args//");
        return sum;
    }

    public static double sum(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(sum(1.5, 2.5));
        System.out.println(sum(10, 20));
        System.out.println(sum(10, 20,30));
    }
}

Expected results;

4.0
this is variant args//30
this is variant args//60

actual results in the console:

4.0
30.0
this is variant args//60

I can’t understand why the results are sum(10, 20)30.0 and not 30 variable arguments.

+4
source share
6 answers

This is because the compiler always makes the choice to use the most specific method.

Since your second call has two arguments, and intcan be converted to doublewithout loss of precision (see JLS, section 5.1. 2 ), the compiler selects a call to your method with two arguments.

IDE int to double.


edit: @OlegEterkhin , . JLS, 15.2.2 , , , .

, :

int x = sum(10, 20);
+6

JLS 15.12.2. , varargs, varargs, :

, Java Java SE 5.0. :

  • (§15.12.2.2) arity. - , . [...]

  • (§15.12.2.3) , arity. - , . [...]

  • (§15.12.2.4) arity, .

, sum(double, double) sum(10, 20) - int double.

+5

:

System.out.println(sum(10, 20));

sum(double a, double b), , .

. 15.12.2. 2: .

+1

Varargs Java

, , , -args, : -

Primitive widening uses the smallest method argument possible
Wrapper type cannot be widened to another Wrapper type
You can Box from int to Integer and widen to Object but no to Long
Widening beats Boxing, Boxing beats Var-args.
You can Box and then Widen (An int can become Object via Integer)
You cannot Widen and then Box (An int cannot become Long)
You cannot combine var-args, with either widening or boxing
+1

varargs. , ( ) varargs ( ).

+1

This behavior is defined in the specification . "Arity variable methods, boxing and unboxing" are processed in the third phase of the method signature resolution, after they first tried to match the signature without using the arity variable methods.

+1
source

Source: https://habr.com/ru/post/1535502/


All Articles