为什么不是Java通INT []以可变参数? [英] Why won't Java pass int[] to vararg?
问题描述
为什么不这样编译?
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);
}
}
据抱怨线5条,他说:
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
但据我(等人对SO )知道, INT ...
相同 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);
}
因为编译器说:
name clash: prints(int[]) and prints(int...) have the same erasure
cannot declare both prints(int[]) and prints(int...) in PrimitiveVarArgs
所以,为什么不是Java让你通过本地阵列一个可变参数的方法?同时,如果请你,给我一个方法来解决这个问题(即提供了一种方法来传递可变参数或数组此方法)。
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).
推荐答案
在您的code修正这个,它会工作:
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)
这篇关于为什么不是Java通INT []以可变参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!