I can set an array like this:
Object[] objects = {new Object()};
However if I have a method:
public void setObject(Object[] objects) {
}
I cannot do the following:
setObject({new Object()});
Why is this? Why doesn't {new Object()}
suffice as an argument but suffices to initialize an Object[]
array?
You can pass an anonymous array :
setObject(new Object[] { new Object() });
Note that the syntax { new Object() }
just works when initializing the array on its declaration. For example:
Object[] arr = { new Object() };
This doesn't work after declaring the array:
Object[] arr;
//uncomment below line and you'll get a compiler error
//arr = { new Object() };
arr = new Object[] { new Object() };
Because you haven't typed the Array. It could be objects, integers, whatever.
The following should work:
setObject(new Object[]{new Object()});
适当的回调是:
setObject(new Object[]{new Object()});
Every Java array has a component type. When used in an initializer, the compiler infers that the type of the new array (the right-hand side) is the same as the declared type (the left-hand side).
When the declaration is missing, the compiler doesn't know what the component type of the array should be. You must be explicit, using the expression setObject(new Object[] { new Object() })
One might wonder why the compiler doesn't infer the type from the declared type of the method parameter, like it does when initializing a variable. But, the compiler resolves the method to call based on the parameter types; if you don't know the method you are calling, you can't infer anything from its parameter types. There's no circularity when initializing a variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.