If you explicitly initialize an object array in Java, the inclusion is different from the new object []?
This question has been asked here, but I especially want to know the specific meaning of the author
I read thinking in Java, 3rd Edition Revision 4.0, Eckel displays this code segment in Chapter 4 initialization and Cleanup:
public class ArrayInit { public static void main(String[] args) { Integer[] a = { new Integer(1),new Integer(2),new Integer(3),}; Integer[] b = new Integer[] { new Integer(1),}; } }
And declare as follows:
I never realized that this was different from Eckel's description As far as I know, they are static size arrays I don't understand that the first is more restrictive than the second
What is he talking about?
Solution
I think this may be what the author refers to
Because of Java 5, we can declare functions using variable parameter lists
public static int newStyleSum(final int... numbers) { int sum = 0; for (final int number : numbers) { sum += number; } return sum; }
They can be used to:
int s = newStyleSum(1,2,3,4);
This function is just grammar sugar Internally, an anonymous array is passed to the function
Before we have this grammar, the above example must be written as:
public static int oldStyleSum(final int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; ++i) { sum += numbers[i]; } return sum; }
And called
int s = oldStyleSum(new int[]{1,4}); // "second" form
But not as good as
int s = oldStyleSum({1,4}); // "first" form (Syntax error)
Even today it is still a grammatical error
This may be what he is talking about Java 5 was published in 2004, so it makes sense for the 2002 book
The new syntax is more flexible and more importantly backward compatible, so we can still do it
int s = newStyleSum(new int[]{1,4});
Or more importantly,
int[] numbers = {1,4}; int s = newStyleSum(numbers);
If we want to