Array initialization syntax when not in a declaration
Solution 1:
Why is this blocked by Java?
You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.
But "why" is immaterial ... the restriction is there, and you have to live with it.
I know how to work around it, but from time to time it would be simpler.
You can write this:
AClass[] array;
...
array = new AClass[]{object1, object2};
Solution 2:
I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.
If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.
In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.
I would say that (and if someone knows better, please correct me) the first example
AClass[] array = {object1, object2}
actually means
AClass[] array = new AClass[]{object1, object2};
but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.
The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.
Solution 3:
I can't answer the why part.
But if you want something dynamic then why don't you consider Collection ArrayList.
ArrrayList can be of any Object type.
And if as an compulsion you want it as an array you can use the toArray() method on it.
For example:
ArrayList<String> al = new ArrayList<String>();
al.add("one");
al.add("two");
String[] strArray = (String[]) al.toArray(new String[0]);
I hope this might help you.