Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList removing elements recover wasted space? [duplicate]

Tags:

java

arraylist

If you have an Array List that has been extended (the array has grown) to contain many elements and these elements are then removed, does the actual array size change to save memory?

In more details, when removing an element from a large Array List, is the reserved memory for the array empty part of the array recovered? It would seem logic that since we expanded the array we might need to use this space and so it will not be touched.

However if we have a really large array list and we only use the first 10 or so elements, will the compiler (or on run time) realize that all the extra space is being wasted and recover it? (Will the actual array size be decreased? (Copying the elements into a smaller array?))

like image 277
A.D Avatar asked Apr 15 '19 09:04

A.D


1 Answers

You can call trimToSize() in order to replace the backing array of the ArrayList with a smaller array that matches the size of the list.

void java.util.ArrayList.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 58
Eran Avatar answered Sep 28 '22 18:09

Eran