If you have an Array List that has been extended (the array has grown) to contain many elements and these elements are then removed, does the actual array size change to save memory?
In more details, when removing an element from a large Array List, is the reserved memory for the array empty part of the array recovered? It would seem logic that since we expanded the array we might need to use this space and so it will not be touched.
However if we have a really large array list and we only use the first 10 or so elements, will the compiler (or on run time) realize that all the extra space is being wasted and recover it? (Will the actual array size be decreased? (Copying the elements into a smaller array?))
You can call trimToSize()
in order to replace the backing array of the ArrayList with a smaller array that matches the size of the list.
void java.util.ArrayList.trimToSize()
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.
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