Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does trimtosize() function works on ensureCapacity() function in ArrayList

Suppose I have an Array List of String. I used Function ensureCapacity() and set its capacity to 50.

But I add only 10 String Elements and rest 40 memory is wasted.

Now after that i use trimToSize() function.

My Question is "Does trimToSize() Function save my 40 memory."?

like image 935
Mohit Gandhi Avatar asked Dec 11 '25 04:12

Mohit Gandhi


1 Answers

I assume you are talking about Java, as the Java ArrayList has those methods that you are mentioning, like trimToSize(). And quoting from the javadoc for that 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.

So the answer is: yes, exactly.

But just to remember you: this will "save" you the space required 40 object references. So it doesn't really matter if you have want store strings, integers, or byte[] objects in that list.

And beyond: unless we are talking resource critical environments; such as some embedded system, you shouldn't worry too much about 40 list slots. Maybe about 100K; or 10 million slots; but not about 40.

like image 65
GhostCat Avatar answered Dec 14 '25 04:12

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!