How to pass an array as a parameter in a Java method?

Code:

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

When I try:

someMethod ( {myObject} );

I received an error in eclipse

But when:

someMethod ( a );

everything goes well. Why the difference? thank you.

Solution

Because the {MyObject} syntax is special syntax sugar, it is only applicable to initializing array variables This is because your job lacks type information; However, in the special case of assignment, the type is completely inferred from the variable

In the first example, the compiler knows that you are allocating an object (this is an object []), so this syntax is allowed In the latter, you don't initialize a variable (and because of the weakness of Java type inference, you can't even completely solve the context of parameter assignment) So it doesn't know what type the array should be, even if it can clearly determine that this is what you want to do (rather than, for example, declaring a block)

call

someMethod ( new Object[] { myObject } )

If you want to define an array in place without using variables

Although the above question answers your question, I notice that the method you call is varargs instead of explicitly requiring an array parameter So in this case, you can simply call

someMethod(myObject);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>