Arrays of objects in methods

Consider the following method signatures:

public fooMethod (Foo[] foos) { /*...*/ }

and

public fooMethod (Foo... foos) { /*...*/ }

Explanation: The former accepts an array of Foo objects as an argument - fooMethod(new Foo[]{..})-, while the latter accepts an arbitrary number of arguments of type Foo and represents them as an array of Foo: s inside the method - fooMethod(fooObject1, fooObject2, etc...).

Java throws a fit if both are defined, claiming they are duplicate methods. I did some detective work and found out that the first declaration really requires an explicit array of Foo objects and the only way to call this method. The second method actually takes an arbitrary number of arguments Foo, and takes an array of Foo objects.

So the question is, since the last method seems more flexible, are there any reasons for using the first example, or have I missed something vital?

+5
source share
4 answers

These methods are actually the same.

This function is called varargs and is a compiler. Behind the scenes, this is being reverted to the previous version.

There is an error if you define a method that takes an Object ... and you send one parameter of type Object []!

+12
source

I would like to add to Shimi's explanation to add that another limitation of the varargs syntax is that vararg should be the last parameter declared. Therefore, you cannot do this:

void myMethod(String... values, int num);

, vararg. , , varargs .

, varargs , args , . Java5 , .

String.format(). varargs .

+3

Java 5, . , , 2+ , , ... .

+1

, , .

, Foo ? Foo []. varargs, "" Foo .

varargs ist string-format ( #, dunno, Java):

string Format(string formatString, object... args)

, , unusal, , varargs.

, -

string Join(string[] substrings, char concatenationCharacter)

.

, vararg paramater.

0

All Articles