4

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 ?

1
  • I guess the Java compiler was not designed to infer the "real type" of the array from its elements... Commented Sep 17, 2012 at 12:06

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Yes, an interesting example for possible list literal syntaxes (and others) was given recently by Brian Goetz on the lambda-dev mailing list
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.