Shrinking an ArrayList to a new size

后端 未结 5 1870
有刺的猬
有刺的猬 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 19:55

    Create a sublist with the range of elements you wish to remove and then call clear on the returned list.

    list.subList(23, 45).clear()
    

    This approach is mentioned as an idiom in the documentation for both List and ArrayList.


    Here's a fully unit tested code example!

    // limit yourHappyList to ten items
    int k = yourHappyList.size();
    if ( k > 10 )
        yourHappyList.subList(10, k).clear();
        // sic k, not k-1
    

提交回复
热议问题