ArrayList in C#

Introduction

What is an Array? An array is a collection of variables of the same type that are referred to by a common name. For example you can create an array for student marks. The Marks are an integer value so you can create an integer array that holds all student marks. Suppose some students have marks from an examination but other students have a grade. A grade is a string value like “A”, ”B” and so on. What do you? You can create two arrays, one for marks that is an integer array and another for grade that is a string array. You have two arrays so you can’t retrieve the result in students sequence because you have marks in the first array then grades in the second array. So when you have multiple types set then you can use an ArrayList. ArrayList is one of the most flexible data structures from C# Collections. An ArrayList contains a simple list of values.

  1. To use an ArrayList you need to add a System.Collections namespace.
  2. ArrayList implements the System.Collections.IList interface using an array whose size is dynamically increased as required.
  3. ArrayList is an alternate of an Array but you can’t implement multi-dimensional arrays using ArrayList.
  4. Array is a fixed size collection whereas an ArrayList's size can be dynamically increased or decreased.
  5. An Array is a collection of variables of the same type whereas an ArrayList is a collection of variables of the same type or multiple types.
  6. The capacity of an ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.
  7. Elements in an ArrayList collection can be accessed using an integer index. Indexes in this collection are zero-based.
  8. The ArrayList collection accepts null as a valid value, an allows duplicate elements.

Add an item on ArrayList

 The Add method on ArrayList appends a new item/element object to the end of the ArrayList. You can add elements in the ArrayList until memory runs out.The objects are stored in the managed heap. Let’s see an example of creating an ArrayList and add two elements using the Add() method of ArrayList.

using System;

using System.Collections;

namespace
ArrayListApplication
{

   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList resultList = new ArrayList();
            resultList.Add(90);

            resultList.Add(95);

           
Console.Read();
        }

    }

} 

Whenever you execute this program you will get that your ArrayList has been populated by elements as per Figure 1.1.


 Adds item in ArrayList
Figure 1.1 Adds item in ArrayList.

Read Items from ArrayList

You can read items from the ArrayList using a foreach loop. Let’s see an example.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList= new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
           
foreach (var item in personList)
            {

               
string arrayItem = string.Format("Name  is {0}", item);
               
Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

} 

You execute this program then get output as in Figure 1.2.

 
Read Data from an ArrayList 
Figure 1.2 Read Data from an ArrayList

ArrayList items are stored on an index basis. Let’s see Figure 1.1 where the first item stored is at index 0 whereas the next item stored at the next index, in other words index 1 so you can also retrieve items from an ArrayList using an index. Let’s see the following code.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
           
for (int i = 0; i < personList.Count;i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList [i]);
               
Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

}
 

When you execute this program you will get the same output as in Figure 1.2. One more point is that you can read items from an ArrayList by an index but you can’t add items in an ArrayList by index.

Insert an Item to ArrayList

You have seen that you can add items to an ArrayList so what is meant by "insert"? The Add method adds an item to the end of the ArrayList whereas Insert adds an item at a specific index position. Let’s see an example where I add an item to index 1.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
           
Console.WriteLine("=====Original List======");
           
for (int i = 0; i < personList.Count; i++)
            {

                Console.WriteLine(arrayItem);
           }

            personList.Insert(1,
"Shaijal");
           
Console.WriteLine("=====Modify List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

}
 

Now you can execute this program and get the results as in Figure 1.3.

 
Insert an Item on index 1 
Figure 1.3 Insert an item at index 1

Remove an Item from ArrayList

You can remove an item or items from an ArrayList. The ArrayList class provides four methods to remove an item or items from it. These methods are:

  1. Remove
  2. RemoveAt
  3. RemoveRange
  4. Clear

Let’s describe each one by one.

1.  Remove

The Remove() method has one parameter that is the object type. You know that each item of the ArrayList is an object type so you need to pass that item in the Remove method to remove that item from the ArrayList. Let’s see an example where the first item is removed from the ArrayList. 

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Shaijal");  
          
Console.WriteLine("=====Original List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
//remove item "Sandeep" from person list
            personList.Remove(
"Sandeep"); 

            Console.WriteLine("=====Modified List======");

            for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

}

You execute this program then get the results as in Figure 1.4.

 
Remove an Item from the ArrayList 
Figure 1.4 Remove an item from the ArrayList

2. RemoveAt

In the previous method you saw that you can remove an item from the ArrayList using the Remove method. Notice one thing, that you need to remember the item to be removed. Suppose you have an ArrayList of complex objects that time you can’t remember the state of an object that will be removed. In this scenario you can use the RemoveAt method of which you only need to pass the index number of the item. Let’s see an example of removing the first item of the ArrayList using index position. 

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Shaijal"); 
           
Console.WriteLine("=====Original List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
//remove first item from person list using index
            personList.RemoveAt(0);
 
           
Console.WriteLine("=====Modified List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

}

When you execute this program you get the same result as in Figure 1.4.

3. RemoveRange

Each of the previous two methods removed a single item at a time. Suppose you want to remove more than one item from the ArrayList, then you need to call these methods multiple times. Alternativley you can use the RemoveRange method that can remove multiple items in a single call. The RemoveRange method has two arguments. The first argument is the beginning index number to be removed and the second parameter is the count yo be removed, in other words how many items you want to remove. But it removes items in sequence. Let’s see an example where the first two items are removed.

 

using System;
using
System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Shaijal"); 
           
Console.WriteLine("=====Original List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
//remove first two item from person list using index
            personList.RemoveRange(0,2);
 
           
Console.WriteLine("=====Modified List======");
           
for (int i = 0; i < personList.Count; i++)
            {

               
string arrayItem = string.Format("Name  is {0}", personList[i]);
               
Console.WriteLine(arrayItem);
            }

           
Console.Read();
        }

    }

}
 

When you execute this program you get the output as in Figure 1.5.

Remove more than one items from the ArrayList
Figure 1.5 Remove more than one items from the ArrayList

Before proceeding I want to tell you that the ArrayList class has a property Count that represents how many items are in the ArrayList. Let’s see an example.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Shaijal");
           
int totalItems = personList.Count;
           
Console.WriteLine(string.Format("Total Number Of Items in ArrayList :{0}",totalItems));
           
Console.Read();
        }

    }

}
 

You run this program then get the results as in Figure 1.6.

Total number of items in the ArrayList

Figure 1.6 Total number of items in the ArrayList

4. Clear

The Clear method of ArrayList removes all the items from the ArrayList but doesn’t reduce the capacity of the ArrayList. The Clear method removes all items from the ArrayList. Let’s see an example.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Shaijal");
           
int totalItems = personList.Count;
           
Console.WriteLine(string.Format("Total Number Of Items in ArrayList :{0}",totalItems));
           
//Remove all items from person list           

            personList.Clear();

            totalItems = personList.Count;
           
Console.WriteLine(string.Format("Total Number Of Items in ArrayList :{0}", totalItems));           

            Console.Read();

        }
    }

}
 

Run the preceding program and you get the results as in Figure 1.7.

 
Output for clear method 
Figure 1.7 Output for clear method

Sorting the ArrayList

You can sort any ArrayList in  ascending order using the Sort() method. The Sort() method sorts the elements of an ArrayList. This method uses Array.Sort, that uses the QuickSort algorithm. Let’s see an example of sorting a person name list.

using System;

using System.Collections;

namespace ArrayListApplication

{
   
class Program
    {

       
static void Main(string[] args)
        {

           
ArrayList personList = new ArrayList();
            personList.Add(
"Sandeep");
            personList.Add(
"Raviendra");
            personList.Add(
"Vinit");
            personList.Add(
"Lokesh");
            personList.Add(
"Prateek"); 
           
Console.WriteLine("=========== Original List================");
            PrintValues(personList);
 
           
//sort the list
            personList.Sort();
 
           
Console.WriteLine("=========== Sorted List================");
            PrintValues(personList);        

            Console.Read();

        }
       
private static void PrintValues(IEnumerable myList)
        {

           
foreach (Object obj in myList)
            {

               
Console.WriteLine("Name is :{0}", obj);
            }           

        }

    }
}

Execute this program and you get results as in Figure 1.8.

 
Sorted ArrayList 
Figure 1.8 Sorted ArrayList

Performance of ArrayList

There is a performance penalty in the use of ArrayList, particularly on value types. This is because boxing occurs, which is a way the runtime turns a value type into an object. Each element or item is added as an object to an ArrayList.

Up Next
    Ebook Download
    View all
    Learn
    View all