I have a method having an array parameter like:
public static void foo(int[] param) {
// Some code
}
And also I can call the method by writing like
foo(new int[3]);
Normally, we declare and initialize an array by new operator or double braces initializer like {1, 2, 3}. For example, int[] foo = new int[3];
or int[] foo = {1, 2, 3};
.
But it's impossible to use double brace initializer as a parameter for a method. {}
is only available for creating an array object.
And here is my question: Are there any differences between new operator and {}
?
If there is, what is it?
Disadvantages of Using Double Braces It creates an extra class every time we use it. Doesn't support the use of the “diamond operator” – a feature introduced in Java 7. Doesn't work if the class we are trying to extend is marked final. Holds a hidden reference to the enclosing instance, which may cause memory leaks.
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces).
Just to complete the other answer, you can have a look at the JLS 8 10.6: you can see that in the grammar a variable initializer is either an expression OR (exclusive) an array initializer (which is not an expression and thus cannot be use when invoking a method).
The {}
as part of a int foo[] = {1, 2, 3};
is what is termed as brace initialization, and is a shortcut for int foo[] = new int[]{1, 2, 3};
because the new int[]
can be inferred from the left hand side.
In the second case foo({1, 2, 3});
no inference of what you intend can be determined as there is no hint as to what the {1, 2, 3}
means, so the compiler complains.
When you rewrite it as foo(new int[]{1, 2, 3});
you're telling the compiler what the item in {}
is meant to represent.
The compiler won't (and does not try) to auto-interpret the {}
expression until it matches - that would lead to potential ambiguities.
There is also this question, which seems to cover exactly the same ground.
As mentioned by @benzonico, it is part of the language specification as to this being a supported syntax, which doesn't include it being used in the invocation of a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With