Array initialization syntax when not in a declaration

后端 未结 4 980
粉色の甜心
粉色の甜心 2020-11-22 06:32

I can write:

AClass[] array = {object1, object2}

I can also write:

AClass[] array = new AClass[2];
...
array[0] = object1;
         


        
4条回答
  •  遇见更好的自我
    2020-11-22 07:08

    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};
    

提交回复
热议问题