java arraylist ensureCapacity not working

后端 未结 8 2065
天命终不由人
天命终不由人 2020-12-03 05:18

Either I\'m doing this wrong or i\'m not understanding how this method works.

ArrayList a = new ArrayList();
a.ensureCapacity(200         


        
8条回答
  •  半阙折子戏
    2020-12-03 06:15

    ArrayList maintains its capacity (the size of the internal array) separately from its size (the number of elements added), and the 'set' method depends on the index already having been assigned to an element. There isn't a way to set the size. If you need this, you can add dummy elements with a loop:

    for (int i = 200; --i >= 0;) a.add(null);
    

提交回复
热议问题