Creating a new ArrayList in Java

后端 未结 9 1971
执念已碎
执念已碎 2021-02-05 00:31

Assuming that I have a class named Class,

And I would like to make a new ArrayList that it\'s values will be of type Class.

My question

9条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 00:53

    If you just want a list:

    ArrayList myList = new ArrayList();
    

    If you want an arraylist of a certain length (in this case size 10):

    List myList = new ArrayList(10);
    

    If you want to program against the interfaces (better for abstractions reasons):

    List myList = new ArrayList();
    

    Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

提交回复
热议问题