TrimToSize method in ArrayList
In this article I will explain the TrimToSize method of ArrayList.
Introduction
TrimToSize method sets the capacity to the actual number of elements in the ArrayList,that means if their are two element in the arraylist then it shows 4 as a capacity of arraylist but if I apply the TrimToSize method and then find the capacity of arraylist it shows two that actually contain in the arraylist.So in this way we can also save the memory.
Example
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("Red");
list.Add("Pink");
list.Add("Orange");
list.Add("Blue");
list.Add("White");
list.Add("Black");
list.Add("Yellow");
list.Add("Gray");
list.Add("Olive");
//find the number of elements contain in the arraylist
Console.WriteLine("The number of element in the arraylist are:" + list.Count);
//find the capacity of arraylist
Console.WriteLine("The capacity of the arraylist are:" + list.Capacity);
//use TrimToSize method
list.TrimToSize();
Console.WriteLine();
//after apply the TrimToSize method the capacity of arraylist will be changed
Console.WriteLine("The number of element in the arraylist are:" + list.Count);
Console.WriteLine("The capacity of the arraylist are:" + list.Capacity);
}
}
}
|
Output
Got a programming related question? You may want to post your question here