Why doesn't Java pass int [] to vararg?

Why is this not compiling?

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); } } 

He 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... matches int[] . This works if it is not a primitive type, such as String , but not for 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 allow you to pass your own array to the varargs method? Also, if you want, suggest me a way to solve this problem (i.e. provide a way to pass variable arguments or an array for this method).

+3
java arrays primitive-types variadic-functions
source share
1 answer

Fix this in the code and it will work:

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

The problem is not varargs, but how you invoke the instance method from a static context. Also, make sure there are no other methods with conflicting signatures, for example, these two methods will look the same with the compiler:

 void prints(int... ints) void prints(int[] ints) 
+10
source share

All Articles