How to pass array as parameter in java method?

13,684

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);
Share:
13,684
user710818
Author by

user710818

Updated on June 05, 2022

Comments

  • user710818
    user710818 almost 2 years

    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.