Passing an array as an argument in the form {}

I can install an array like this:

Object[] objects = {new Object()}; 

However, if I have a method:

 public void setObject(Object[] objects) { } 

I can not do the following:

 setObject({new Object()}); 

Why is this? Why is there no {new Object()} as an argument, but is it enough to initialize the Object[] array?

+2
source share
4 answers

You can pass an anonymous array:

 setObject(new Object[] { new Object() }); 

Note that the syntax { new Object() } only works when initializing an array when it is declared. For instance:

 Object[] arr = { new Object() }; 

This does not work after the array declaration:

 Object[] arr; //uncomment below line and you'll get a compiler error //arr = { new Object() }; arr = new Object[] { new Object() }; 
+8
source

Because you did not type an array. It can be objects, integers, anything.

The following should work:

 setObject(new Object[]{new Object()}); 
+3
source

The correct callback:

 setObject(new Object[]{new Object()}); 
+1
source

Each Java array has a component type. When used in the initializer, the compiler indicates that the type of the new array (right side) is the same as the type of declaration (left side).

When there is no declaration, the compiler does not know what the type of the component of the array should be. You must be explicit using the expression setObject(new Object[] { new Object() })

One may ask why the compiler does not deduce the type from the declared type of the method parameter, as it happens when the variable is initialized. But the compiler allows a call method based on parameter types; if you don’t know the method you are calling, you cannot deduce any of its parameter types. There is no rounding when initializing a variable.

+1
source

Source: https://habr.com/ru/post/945991/