Count element in ArrayList

In this chapter you will learn:

  1. How to get elements in an ArrayList
  2. Capacity and element count
  3. How to release memory down to the element size

Count elements

The following code gets the number of elements.

using System; // j a  va 2  s. c  o m
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Initial number of elements: " + al.Count); 
 
    Console.WriteLine("Adding 6 elements"); 
    // Add elements to the array list 
    al.Add('C'); 
    al.Add('A'); 
    al.Add('E'); 
    al.Add('B'); 
    al.Add('D'); 
    al.Add('F'); 
 
    Console.WriteLine("Number of elements: " + al.Count); 
  }
}

The code above generates the following result.

Capacity and element count

The capacity is the number of elements an ArrayList can store before allocating more memory. The element count is the current number of elements an ArrayList has.

using System; //from j  a  v  a  2 s .  co m
using System.Collections; 
 
class MainClass { 
  public static void Main() { 
    ArrayList al = new ArrayList(); 
     
    Console.WriteLine("Adding 6 elements"); 
    al.Add('C'); 
    al.Add('A'); 
    al.Add('E'); 
    al.Add('B'); 
    al.Add('D'); 
    al.Add('F'); 
 
    Console.WriteLine("Add enough elements to force ArrayList to grow. Adding 20 more elements"); 
    
    for(int i=0; i < 20; i++) 
      al.Add((char)('a' + i)); 
    Console.WriteLine("Current capacity: " + 
                       al.Capacity); 
    Console.WriteLine("Number of elements after adding 20: " + 
                       al.Count); 
    Console.Write("Contents: "); 
    foreach(char c in al) 
      Console.Write(c + " "); 
    Console.WriteLine("\n"); 
  }
}

The code above generates the following result.

Trim the size

The following code uses the TrimToSize() method to reduce the capacity of ArrayList.

using System;/* j a v a 2  s . co m*/
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");
    

    string[] anotherStringArray = {"Here's", "some", "more", "text"};
    myArrayList.SetRange(0, anotherStringArray);

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

  }
}

Next chapter...

What you will learn in the next chapter:

  1. Using Indexer of an ArrayList