As the title mentions, if I create an ArrayList with initial capacity 500 and then clear it after some time will its capacity still be 500 ? or do I need to re-init it for that ?
Yes, it preserves its capacity. (at least, not in the implementation of the Oracle VM):
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
Just to be clear: an ArrayList
is backed by an array (e.g. int[] for ArrayList) and that array is expanded whenever you go over capacity by creating a new array and copying things over. Clearing will not (as seen in the code) create a new smaller array, copy things there, and destroy the old big array.
No, arrayList's capacity is not changed if you remove the elements from the list. But you can do that yourself using trimToSize.
In general, you don't need to worry about the capacity as it's increased as you add more elements. The possible reason to worry about capacity is performance due to frequent re-allocation. Otherwise, you don't need to worry about re-initializing the capacity.
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