Calling varargs element blending method and element array does not work

I have a method with the following signature:

public void foo(String... params); 

Thus, all these calls are valid:

 foo("Peter", "John"); foo(new String[] { "Peter", "John" }); 

But why is this not valid?

 foo("Peter", new String[] { "John" }); 
+6
java
source share
5 answers

From docs :

Three periods after the final parameter type indicate that the final argument can be passed as an array or as a sequence of arguments.

You cannot pass an argument and an array.

+8
source share

This is because you are actually trying to pass an Array containing a String and another array.

+2
source share

Because it is not the same thing. You just can't mix and match like that. Invalid in your example will work with the function signature as follows:

 public void foo(String head, String ... tail) 
0
source share

This method

 public void foo(String... params); 

is just a handy version of this:

 public void foo(String[] params); 

And therefore, you can call it with a variable number of strings (which will be converted to a String array by the compiler) or a String array, but the combination will not work by design.

0
source share

Think about it. What if you have a method like this:

 public void foo(Object... objects); 

And tried to call him like this:

 foo("bar", new Object[] { "baz" }); 

Should Object[] in the second position be considered as one Object in the varargs call, or should it be "extended"? This will lead to very confusing behavior.

0
source share

All Articles