If I understand ArrayLists, they're backed by an array which is automatically resized when its full. On calling clear() is the ArrayList resized to the smallest possible array size?
The answer is simply no. If you observe source code of the ArrayList class, you will get the answer. There is no operation to decrease capacity of ArrayList's remove() method.
Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.
ArrayList will grow and shrink implicitly.
To reset the capacity of the ArrayList, call TrimToSize or set the Capacity property directly.
No it's not, and this is an issue to keep in mind. Assuming ArrayList's internal Object[] grew up to 1000000 elements. Now you call ArrayList.clear(). This sets all 1000000 elements to null and internal size to 0. Nulling 1000000 is a time expensive operation and ArrayList will still occupy 1000000 x 4 bytes Object[] on the heap. You can call ArrayList.trimToSize() after clear() but there's a catch - you first cleared 1000000 elements then threw them away. In this situation a much better solution is to just recreate your ArrayList - new ArrayList().
The size is set to 0 but there's no resize that happens explicitly
Here's the actual code.
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
Please check this link.
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