ArrayList shrinking
We know that ArrayList can expand or shrink dynamically. Can someone explain how the process of shrinking is handled internally?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sudha NarayananPosted Oct 8, 2007, 6:57 AM
AlanPosted Oct 8, 2007, 6:46 AM
The ArrayList class has a private field called _items which is of type object[] and which holds references to the objects added to the ArrayList.
When you shrink the ArrayList by calling the TrimToSize() method or by setting the Capacity property explicitly, a new object array of the reduced size is created and the elements of the existing _items array are copied over to it. The new array is then assigned to the _items field.
As there will no longer be any references to the old array, the memory will be reclaimed by the garbage collector in due course.