Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrinking an ArrayList to a new size

Tags:

java

arraylist

Do I really need to implement it myself?

private void shrinkListTo(ArrayList<Result> list, int newSize) {   for (int i = list.size() - 1; i >= newSize; --i)   list.remove(i); } 
like image 695
ripper234 Avatar asked Jul 26 '09 13:07

ripper234


People also ask

How do you shrink an 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.

Can you change the size of an ArrayList?

The size of an ArrayList cannot be changed after the ArrayList is initialized. Immediately looking at the question, I would think the answer would be false. If you initialize an ArrayList, you can continue adding unlimited elements to it and the ArrayList will automatically resize.

Can we shrink ArrayList in Java?

Java ArrayList s do not shrink (even though, of course they do grow) automatically.

How much does the ArrayList size increase after resizing?

The grow method in the ArrayList class gives the new size array. In Java 8 and later The new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity. It uses Arrays.


1 Answers

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 
like image 54
mP. Avatar answered Sep 22 '22 11:09

mP.