Curiosity of an array of Java objects

Why so if you have, say, these functions:

void func1(Object o){ //some code } void func1(Object[] o){ //some code } 

You can call, for example:

 func1("ABC"); 

but not :

 func1({"ABC", "DEF"}); // instead having to write: func1(new Object[]{"ABC", "DEF"}); 

Question: Is there any special reason why the constructor should be called on arrays?

+4
source share
4 answers

"array initializer" is only available for declarations / assignments:

 Object[] o = { 1, 2 }; 

Or for "array creation expression" :

 new Object[] { 1, 2 }; 

Not for method calls:

 // Doesn't work: func1({1, 2}); 

It is as it is ... You can read about it in JLS, chapter 10.6. Array initializers . Exposure:

An array initializer can be specified in a declaration ( ยง8.3 , ยง9.3 , ยง14.4 ) or as part of an array creation expression ( ยง15.10 ) to create an array and provide some initial values.

Besides the fact that it is not defined in JLS right now, there seems to be no reason why a future version of Java will not allow the use of array literals / arrays in other contexts. An array type can be inferred from the context in which the array literal is used, or from the variable initializers contained in it

Of course, you can declare func1 argument to varargs. But then you have to be careful with overloading, as this can cause some confusion on the site of the call site

+5
source

It has been suggested that Java SE 5.0 will have a literal array entry. Unfortunately, we got varargs instead, and it's all fun.

So, to answer the question of why, the language is the same. You can see literals in a later version of Java.

+5
source

You are trying to initialize an inline array that Java does not yet support.

I assume that you could achieve the desired result with varargs if you want, but if you need to pass an array to a method, you should initialize it the way Java likes to initialize the array.

+1
source

When you call func1("ABC") , an object of type String with the value "ABC" is created automatically using java.

To create any object other than String , you need to use new .

0
source

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


All Articles