Set the capacity to the actual number of elements in the ArrayList in CSharp

Description

The following code shows how to set the capacity to the actual number of elements in the ArrayList.

Example


//from w  w w  .j  a  va2s  .com
using System;
using System.Collections;

class MainClass
{
  public static void Main()
  {
    ArrayList myArrayList = new ArrayList();
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    myArrayList.Add("A");
    
    Console.WriteLine("myArrayList.Capacity = " + myArrayList.Capacity);
    
    string[] anotherStringArray = {"Here's", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

    Console.WriteLine("myArrayList.Capacity = " + myArrayList.Capacity);

    myArrayList.TrimToSize();
    Console.WriteLine("myArrayList.Capacity = " + myArrayList.Capacity);

  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary