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.
To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.
You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference).
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
You can pass an entire array, or a single element from an array, to a method. Notice that the int [ ] indicates an array parameter. Notice that passing a single array element is similar to passing any single value. Only the data stored in this single element is passed (not the entire array).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With