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

我是研究僧i 提交于 2019-11-29 22:50:46

问题


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).


回答1:


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)


来源:https://stackoverflow.com/questions/25394998/why-wont-java-pass-int-to-vararg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!