Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 274
user710818 Avatar asked Jul 04 '12 16:07

user710818


People also ask

How do you pass an array as a parameter in Java?

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.

Can an array be a parameter in a method in Java?

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).

Can arrays be passed as parameters to methods?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

Can an entire array be passed as a parameter Java?

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).


1 Answers

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);
like image 110
Andrzej Doyle Avatar answered Oct 07 '22 15:10

Andrzej Doyle