The {}
construct is called an array initializer, and it is used to initialize an array in Java. (Reference: Section 10.6: Array Initializers from The Java Language Specification, Third Edition.)
The reason why passing {1, 2, 3}
itself is not valid is because there is no type information associated with the initializer.
Therefore, one must let the compiler know the type of the array is by writing new Type[]
, where the Type
is the type for which the array is made for.
The following are all valid use of the array initializer:
new String[] {"Hello, "World"}
new Character[] {'A', 'B'}
new Runnable[] {new Runnable() {public void run() {}}, new Runnable() {public void run() {}}
As can be seen, this notation can be used for many data types, so it's not something that is specific for integers.
As for:
int[] a = {1, 2, 3};
The reason why the above is valid is because the type information is provided to the compiler in the variable type declaration, which in this case is int[]
. What the above is implying is the following:
int[] a = new int[] {1, 2, 3};
Now, if we have new int[] {1, 2, 3}
, we are able to create a new int[]
array in place, so that can be handled as any other int[]
array would -- it's just that it doesn't have a variable name associated with it.
Therefore, the array created by new int[] {1, 2, 3}
can be sent into an method or constructor that takes a int[]
as its argument:
new Quicksort(new int[] {1, 2, 3}); // This will work.