Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Java pass int[] to vararg? [duplicate]

Why won't this compile?

public class PrimitiveVarArgs
{
    public static void main(String[] args)
    {
        int[] ints = new int[]{1, 2, 3, 4, 5};
        prints(ints);
    }

    void prints(int... ints)
    {
        for(int i : ints)
            System.out.println(i);
    }
}

It complains about line 5, saying:

method prints in class PrimitiveVarArgs cannot be applied to given types;
  required: int[]
  found: int[]
  reason: varargs mismatch; int[] cannot be converted to int

but as far as I (and others on SO) know, int... is the same as int[]. This works if it's a non-primitive type, like String, but not on primitives.

I can't even add this method:

void prints(int[] ints)
{
    for(int i : ints)
        System.out.println(i);
}

because the compiler says:

name clash: prints(int[]) and prints(int...) have the same erasure

cannot declare both prints(int[]) and prints(int...) in PrimitiveVarArgs

so, why doesn't Java let you pass a native array to a varargs method? Also, if you would please, offer me a way to solve this issue (i.e. provide a way to pass variable arguments or an array to this method).

like image 982
Ky. Avatar asked May 17 '26 07:05

Ky.


1 Answers

Fix this in your code and it'll work:

static void prints(int... ints) // notice the static keyword at the beginning!

The problem is not with the varargs, it's with the way you're calling an instance method from a static context. Also, make extra-sure that there are no other methods with conflicting signatures, for example these two methods will look the same to the compiler:

void prints(int... ints)
void prints(int[]  ints)
like image 94
Óscar López Avatar answered May 18 '26 19:05

Óscar López