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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 anObject[]), 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
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