Does the capacity of an ArrayList
decrease when we remove elements?
No. This is an implementation detail, but AFAIK no (standard) implementation of the ArrayList
class has ever reduced the capacity automatically of a list automatically when elements are deleted.
If the ArrayList
capacity doesn't decrease, could this lead to performance issues?
Well, in general no.
Firstly, lists typically don't shrink. (Most lists have a relatively short lifetime. They are treated, built by appending and then processed. List element removal is relatively unusual ... though it depends on the application.) So the question is moot, most of the time.
Secondly, unless a ArrayList
is grossly oversized, then the unused space at beyond the end of the list doesn't impact performance significantly. Indeed the only time when anything is directly impacted at all is when the list is marked and copied by the garbage collector. And the impact is relatively small, because the region beyond the logical end of an ArrayList
is always cleared to null
to prevent memory leaks.
It is worth noting that an ArrayList
that is creating by appending to an initially empty list is liable to have a backing array that is on average 50% too big. This is because ArrayList
s builtin strategy for expanding the backing array is to double its size. This what makes append
an amortized O(1)
operation.
Thirdly, a delete
or similar operation doesn't "know" what is going to happen next with the list, so it cannot judge whether resizing is an appropriate thing to do.
If your application really needs to, it could call trimToSize()
after deleting elements. However, beware:
Calling trimToSize()
is expensive. The ArrayList
implementation is going to create a brand new backing array (of exactly the right size) and copy all of the array elements.
The next time you insert or append an element to the ArrayList
after a trimToSize()
, the operation will be forced to reallocate the backing array ... again. And the new capacity will be double the current list size.
In fact, if you think about it automatically shrinking an ArrayList
after each deletion is pretty much guaranteed to be BAD for performance due to the reallocations and copying it would trigger.
Insertion and deletion would become significantly more expensive than it currently is, and for some usage patterns append
would become O(N)
on average.