java arraylist ensureCapacity not working

后端 未结 8 2047
天命终不由人
天命终不由人 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:07

    So as others have mentioned ensureCapacity isn't for that. It looks like you want to start out with an ArrayList of 200 nulls? Then this would be the simplest way to do it:

    ArrayList a = new ArrayList(Arrays.asList( new String[200] ));
    

    Then if you want to replace element 190 with "test" do:

    a.set(190, "test");
    

    This is different from

    a.add(190, "test");
    

    which will add "test" in index 190 and shift the other 9 elements up, resulting in a list of size 201.

    If you know you are always going to have 200 elements it might be better to just use an array.

提交回复
热议问题