ArrayList.TrimToSize Method is used to set the capacity to the actual number of elements in the ArrayList. It can be used to minimize a collection’s memory overhead if no new elements will be added to the collection.
Note: This method is an O(n) operation, where n is Count.
public virtual void TrimToSize ();
Exception: This method will give NotSupportedException if the ArrayList is read-only or has a fixed size.
Below given are some examples to understand the implementation in a better way:
Before trimming the capacity is: 8 After trimming the capacity is: 6
Before Using TrimToSize Method: Count: 6 Capacity: 8 Values are: C# Java C++ DSA Python Web After Using TrimToSize Method: Count: 6 Capacity: 6 Values are: C# Java C++ DSA Python Web After Using Clear Method: Count: 0 Capacity: 6 Values are: After Again Using TrimToSize Method: Count: 0 Capacity: 4 Values are:
- C# | Setting the capacity to the actual number of elements in a SortedList object
- C# | Creating an ArrayList having specified initial capacity
- C# | Get or set the number of elements that the ArrayList can contain
- C# | Get the number of elements actually contained in the ArrayList
- C# | Copy the elements of collection over a range of elements in ArrayList
- C# | Adding the elements to the end of the ArrayList
- C# | Adding elements to the end of the ArrayList
- C# | Sort the elements in the ArrayList
- C# | Remove all elements from the ArrayList
- C# | ArrayList whose elements are copies of the specified value
- C# | Remove a range of elements from the ArrayList
- C# | Getting an enumerator for a range of elements in the ArrayList
- C# | Getting a subset of the elements from the source ArrayList
- C# | Copying the elements of ArrayList to a new array
- C# | Reverse the order of the elements in the entire ArrayList or in the specified range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.