Uninitialized Array Assignment Syntax
Java allows for concise initialization of arrays within declarations:
AClass[] array = {object1, object2};
However, attempting to assign an uninitialized array with curly braces results in a compiler error:
AClass[] array; ... array = {object1, object2}; // Error
Reason for Restriction
The specific reason for this restriction is unclear. It may be due to grammatical complexities or the desire to maintain consistency in Java's syntax.
Workaround
Although not as concise, you can initialize an uninitialized array with the new operator and then assign elements explicitly:
AClass[] array; ... array = new AClass[2]; ... array[0] = object1; array[1] = object2;
Simplified Example
Using this workaround in the provided code snippet simplifies the array initialization logic:
public void selectedPointsToMove(cpVect coord) { if (tab == null) { if (arePointsClose(coord, point1, 10)) tab = new cpVect[]{point1}; else if (arePointsClose(point2, coord, 10)) tab = new cpVect[]{point2}; else tab = new cpVect[]{point1, point2}; } }
The above is the detailed content of Why Does Java Prevent Uninitialized Array Assignment with Curly Braces?. For more information, please follow other related articles on the PHP Chinese website!