Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use `new` with an inline-initialized array? [duplicate]

Tags:

java

arrays

As far as I can tell, this code:

int[] numbers = new int[] { 1, 2 };

is the same as this code:

int[] numbers = { 1, 2 };

In fact, the compiled .class disassembles to the same code:

 1: newarray       int
 3: dup
 4: iconst_0
 5: iconst_1
 6: iastore
 7: dup
 8: iconst_1
 9: iconst_2
10: iastore
11: astore_1
12: iconst_2

However, similar code does not always perform the same way, or even compile. For example, consider:

for (int i : new int[] { 1, 2 }) {
    System.out.print(i + " ");
}

This code (in a main method) compiles and prints 1 2. However, removing the new int[] to make the following:

for (int i : { 1, 2 }) {
    System.out.print(i + " ");
}

generates multiple compile-time errors, beginning with

Test.java:3: error: illegal start of expression
for (int i : {1, 2} ) {
             ^

I would assume that the difference between these two examples is that in the first example (with int[] numbers), the type int is explicitly stated. However, if this is the case, why can't Java infer the type of the expression from the type of i?

More importantly, are there other cases where the two syntaxes differ, or where it is better to use one than the other?

like image 958
wchargin Avatar asked May 28 '13 05:05

wchargin


1 Answers

From JLS #10.6. Array Initializers

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.

like image 103
Amit Deshpande Avatar answered Oct 29 '22 15:10

Amit Deshpande