Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object array curiosity

Tags:

java

Why is it that, if you have, let's 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 needs to be called on arrays ?

like image 234
CosminO Avatar asked Dec 21 '22 16:12

CosminO


1 Answers

The "array initialiser" is only available for declarations / assignments:

Object[] o = { 1, 2 };

Or for "array creation expressions":

new Object[] { 1, 2 };

Not for method calls:

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

It's the way it is... You can read about it in the JLS, chapter 10.6. Array Initializers. An extract:

An array initializer may 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.

Apart from it not being defined in the JLS right now, there seems to be no reason why a future Java version wouldn't allow array initialisers / array literals to be used in other contexts. The array type could be inferred from the context in which an array literal is used, or from the contained variable initialisers

Of course, you could declare func1 to have a varargs argument. But then you should be careful about overloading it, as this can cause some confusion at the call-site

like image 67
Lukas Eder Avatar answered Jan 02 '23 13:01

Lukas Eder