Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ArrayList.clear() resize the array to the smallest possible size?

Tags:

java

arraylist

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?

like image 494
A A Avatar asked Dec 22 '12 09:12

A A


People also ask

Does ArrayList resize after remove?

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.

Does ArrayList resize automatically?

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.

Does ArrayList shrink in size?

ArrayList will grow and shrink implicitly.

How do you reset the size of an ArrayList?

To reset the capacity of the ArrayList, call TrimToSize or set the Capacity property directly.


2 Answers

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().

like image 171
Evgeniy Dorofeev Avatar answered Oct 08 '22 01:10

Evgeniy Dorofeev


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.

like image 30
Srinivas Avatar answered Oct 08 '22 01:10

Srinivas