CosminO
CosminO

Reputation: 5226

Java object array curiosity

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 ?

Upvotes: 4

Views: 141

Answers (4)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

There was a suggestion that Java SE 5.0 was going to have an array literal notation. Unfortunately, we got varargs instead, with all the fun that goes with that.

So to answer the question of why, the language is just like that. You may see list literals in a later version of Java.

Upvotes: 5

Lukas Eder
Lukas Eder

Reputation: 221135

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

Upvotes: 5

Pete Slater
Pete Slater

Reputation: 11

You are trying to perform inline array initialization which Java doesn't really support yet.

I suppose you could achieve the desired result using varargs if you so wished, but if you need to pass in an array to a method, you have to initialise it the way Java likes an array to be initialised.

Upvotes: 1

basiljames
basiljames

Reputation: 4847

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

For creating any other object other than of type String you need to used the new operator.

Upvotes: 0

Related Questions