Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the capacity of ArrayList decrease when we remove elements?

ArrayList have a default capacity of 10 objects. As the size exceeds 10 objects, an ArrayList will internally increase its capacity. Does the capacity decrease when we remove the object from ArrayList.

If the ArrayList capacity doesn't decrease, could this lead to performance issues?

like image 515
Santosh Pashupati Avatar asked May 23 '14 13:05

Santosh Pashupati


People also ask

What happens when you remove an element from an ArrayList?

If you call ArrayList. remove() the element at the given index is removed from the list (and all elements following it move down one index). The object itself still exists, no memory has been freed yet.

Does an ArrayList shrink automatically?

Java ArrayList s do not shrink (even though, of course they do grow) automatically.

Can an ArrayList change size?

The size of an ArrayList cannot be changed after the ArrayList is initialized.

How ArrayList increase its capacity?

However, ensureCapacity() method of java. util. ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.


Video Answer


1 Answers

It doesn't decrease this automatically. From the doc.

    public void 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.

like image 97
John Avatar answered Oct 09 '22 02:10

John