A A
A A

Reputation: 113

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

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?

Upvotes: 11

Views: 4798

Answers (4)

Srinivas
Srinivas

Reputation: 1790

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.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

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

Upvotes: 15

Peter Lawrey
Peter Lawrey

Reputation: 533530

to reduce the size you need to use trimToSize () potentially after clearing it. generally this isn't done as it doesn't make much difference unless you array looking to save many MB. A more common solution is to replace the ArrayList in that situation. (I am not saying that is better)

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

The size is set to zero. arrayList.clear() sets all the objects contained in an arraylist to null. But this does not ensure that all the objects contained in the arraylist will be garbage collected.The objects which have references elsewhere will not be Garbage collected till all references are removed.

Upvotes: 0

Related Questions