ArrayList shrinking
We know that ArrayList can expand or shrink dynamically. Can someone explain how the process of shrinking is handled internally?
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Oct 8, 2007, 2:46 AM EDT
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.
Sudha Narayanan3 reputationPosted Oct 8, 2007, 2:57 AM EDT