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."?
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.