user710818
user710818

Reputation: 24248

How to pass array as parameter in java method?

Code:

Object[] a={ myObject};
someMethod(Object ...arg);

when I try:

someMethod ( {myObject} );

I receive error in Eclipse.

but when:

someMethod ( a );

all ok. Why this difference? Thanks.

Upvotes: 11

Views: 13977

Answers (2)

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

Because the { myObject } syntax is special syntactic sugar which only applies when you're initialising an array variable. This is because on its own the assignment lacks type information; but in the special case of assignment the type is fully inferred from the variable.

In the first example, the compiler knows you're assigning to a (which is an Object[]), so this syntax is allowed. In the latter you aren't initialising a variable (and due to a weakness in Java's type inference, it won't even fully work out the context of the parameter assignment either). So it wouldn't know what type the array should be, even if it could unambiguously determine that that's what you're trying to do (as opposed to e.g. declaring a block).

Calling

someMethod ( new Object[] { myObject } )

would work if you want to define the array in-place without using a variable.


While the above answers your question as asked, I notice that the method you're calling is varargs rather than explicitly requiring an array paramter. So in this case you could simply call

someMethod(myObject);

Upvotes: 21

user805774
user805774

Reputation:

someMethod(new Object[] { "" });

Should do the trick!

Upvotes: 6

Related Questions