简体   繁体   中英

Behavior of method overloading with varargs

I have two overloaded methods with varargs int and long. When I run a test passing integer it seems to prefer the varargs long method. Whereas, if I make the methods static and run with an integer it seems to prefer the varargs int method. What's going on here?

void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varagrs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varagrs(1);
    staticvarargs(1);
}

Output:

Inside long varargs 1

Inside static int varargs 1

EDIT: I should've chosen better method names. There was a typo varargs, varagrs. Thanks zhong.j.yu for pointing that out.

Corrected code and expected behavior:

void varargs(int... i){

    System.out.println("Inside int varargs");
    for(int x : i)
        System.out.println(x);
}

void varargs(long... l){

    System.out.println("Inside long varargs");
    for(long x : l)
        System.out.println(x);
}

static void staticvarargs(int...i)
{
    System.out.println("Inside static int varargs");
    for(int x : i)
        System.out.println(x);
}

static void staticvarargs(long...l)
{
    System.out.println("Inside static long varargs");
    for(long x : l)
        System.out.println(x);
}

public static void main(String args[]){
    VarArgs va = new VarArgs();
    va.varargs(1);
    staticvarargs(1);
}

Output:

Inside int varargs 1

Inside static int varargs 1

It's a typo

void varagrs(long... l){
         ^^ 

That's why it's nice to have an IDE with spell checking (eg IntelliJ)

After fixing the typo, the compiler chooses (int...) over (long...) because int is a subtype of long (4.10.1) , so the 1st method is more specific (15.12.2.5) . Note though int[] is not a subtype of long[] (4.10.3) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM