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); }
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.
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.
Java ArrayList s do not shrink (even though, of course they do grow) automatically.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With