Should I use `new` with an inline array?

As far as I can tell, this code is:

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

matches this code:

 int[] numbers = { 1, 2 }; 

In fact, the compiled .class parses 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 do the same or even compiles. For example, consider:

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

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

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

generates multiple compile-time errors, starting with

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

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

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

+6
source share
1 answer

From JLS #10.6. Array Initializers JLS #10.6. Array Initializers

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

+2
source

Source: https://habr.com/ru/post/945982/


All Articles