Array initialization syntax when not in a declaration

后端 未结 4 1067
粉色の甜心
粉色の甜心 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:26

    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 al = new ArrayList();
                al.add("one");
                al.add("two");
                String[] strArray = (String[]) al.toArray(new String[0]);
    

    I hope this might help you.

提交回复
热议问题