Shrinking an ArrayList to a new size

后端 未结 5 1888
有刺的猬
有刺的猬 2020-12-29 19:13

Do I really need to implement it myself?

private void shrinkListTo(ArrayList list, int newSize) {
  for (int i = list.size() - 1; i >= newSi         


        
5条回答
  •  北海茫月
    2020-12-29 20:08

    use ArrayList#removeRange() method:

    protected void removeRange(int fromIndex, int toIndex)

    Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)

    then use ArrayList#trimToSize() method:

    Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.

提交回复
热议问题