EA.
EA.

Reputation: 5580

Calling varargs method mixing elements and array of elements does not work

I have a method with the following signature:

public void 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" });

Upvotes: 8

Views: 3847

Answers (5)

ColinD
ColinD

Reputation: 110104

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.

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299218

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.

Upvotes: 0

Pointy
Pointy

Reputation: 414036

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)

Upvotes: 0

dogbane
dogbane

Reputation: 274878

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.

Upvotes: 10

Lavir the Whiolet
Lavir the Whiolet

Reputation: 1016

That's because in fact you try to pass Array containing String and another Array.

Upvotes: 2

Related Questions