Java two varargs in one method

后端 未结 12 2179
小鲜肉
小鲜肉 2020-11-27 21:08

Is there any way in java, to create a method, which is expecting two different varargs? I know, with the same object kind it isn\'t possible because the compiler does\'nt kn

12条回答
  •  执念已碎
    2020-11-27 21:54

    Only one vararg is allowed. This is because multiple vararg arguments are ambiguous. For example, what if you passed in two varargs of the same class?

    public void doSomething(String...args1, String...args2);
    

    Where does args1 end and args2 begin? Or how about something more confusing here.

    class SuperClass{}
    class ChildClass extends SuperClass{}
    public void doSomething(SuperClass...args1, ChildClass...args2);
    

    ChildClass extends SuperClass, and so is can legally exist in args1, or args2. This confusion is why only one varargs is allowed.

    varargs must also appear at the end of a method declaration.

    Just declare the specific type instead as 2 arrays.

提交回复
热议问题