Calling varargs method mixing elements and array of elements does not work
I have a method with the following signature:
public vo开发者_StackOverflowid foo(String... params);
So all of these calls are valid:
foo("Peter", "John");
foo(new String[] { "Peter", "John" });
But why is this one not valid?
foo("Peter", new String[] { "John" });
From the docs:
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
You can't pass an argument and an array.
That's because in fact you try to pass Array containing String and another Array.
Because it's not the same thing. You just can't mix and match like that. The invalid one in your example would work with a function signature like this:
public void foo(String head, String ... tail)
This method
public void foo(String... params);
is just a convenience version of this one:
public void foo(String[] params);
And hence you can call it with a variable number of Strings (that will be converted to a String array by the compiler) or a String array, but a combination won't work, by design.
Think about it. What if you had a method like this:
public void foo(Object... objects);
And tried to call it like this:
foo("bar", new Object[] { "baz" });
Should the Object[]
in the second position be treated as a single Object
in the varargs call or should it be "expanded"? This would lead to very confusing behavior.
精彩评论