6

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?))

A.D
  • 427
  • 1
  • 4
  • 12
  • 1
    @AxelH hadn't found that one, but I prefer Eran's answer below ;) – A.D Apr 15 '19 at 09:35
  • 2
    And your question is better too! – AxelH Apr 15 '19 at 09:49
  • there are collections in the java world that trim their sizes, but very often this is not needed, as you would only "trim" and do allocations next... that it why use that `trimToSize` with care. – Eugene Apr 17 '19 at 18:10

1 Answers1

10

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.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
Eran
  • 387,369
  • 54
  • 702
  • 768
  • So there is a way but it is never done automatically, good to know ! – A.D Apr 15 '19 at 09:34
  • 1
    I believe it is safe to guess that this would be too complex to know when is the best time to do it automatically without having a performance issues. In the other hand, the grows is necessary for the program to work so it is done as needed. – AxelH Apr 15 '19 at 09:48
  • @AxelH yes, have your array size be reduced and increased over and over would really hit the efficiency – A.D Apr 15 '19 at 09:50