Array Initialization Syntax for Non-Declared Arrays
In Java, initializing arrays presents nuances when the array is not declared simultaneously. While the following syntax is valid:
AClass[] array = {object1, object2};
and this syntax is also acceptable:
AClass[] array = new AClass[2]; ... array[0] = object1; array[1] = object2;
the following code is not allowed:
AClass[] array; ... array = {object1, object2};
Reason for the Restriction
The reason for this restriction remains a mystery, possibly due to underlying grammatical reasons. It was not present in Java 1.0 but was introduced in later versions.
Workaround
One workaround is to use this syntax:
AClass[] array; ... array = new AClass[]{object1, object2};
The above is the detailed content of Why Can't I Initialize a Non-Declared Java Array Directly with Curly Braces?. For more information, please follow other related articles on the PHP Chinese website!