C# - ArrayList Class



The ArrayList represents an ordered collection of an object that can be indexed individually. It is an alternative to an array. However, unlike an array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation and allows for adding, searching, and sorting items in the list.

Creating and Initializing an ArrayList

You can create and initialize an ArrayList by using the ArrayList class from the System.Collections namespace.

You can either create an empty ArrayList and then add elements, or initialize it with values directly.

Syntax

This syntax demonstrates how to create and initialize an ArrayList:

// Creating an empty ArrayList
ArrayList list1 = new ArrayList();

// Adding elements
list1.Add(10);
list1.Add("Hello");
list1.Add(3.5);

// Creating and initializing an ArrayList with values
ArrayList list2 = new ArrayList { 1, "World", 2.5 };

ArrayList Example

Let's see a basic ArrayList example showcasing how to add elements, retrieve the capacity and count, and iterate through the list −

using System;
using System.Collections;

namespace CollectionApplication {
   class Program {
      static void Main(string[] args) {
         ArrayList al = new ArrayList();
         
         Console.WriteLine("Adding some numbers:");
         al.Add(45);
         al.Add(78);
         al.Add(33);
         al.Add(56);
         al.Add(12);
         al.Add(23);
         al.Add(9);
         
         Console.WriteLine("Capacity: {0} ", al.Capacity);
         Console.WriteLine("Count: {0}", al.Count);
         
         Console.Write("Content: ");
         foreach (int i in al) {
            Console.Write(i + " ");
         }
         
         Console.WriteLine();
         Console.Write("Sorted Content: ");
         al.Sort();
         foreach (int i in al) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78    

Accessing Elements from an ArrayList

You can access and modify elements from an ArrayList by using the index position. In an ArrayList index starts with 0.

Example

This example demonstrates how to access and update elements in an ArrayList:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arrayList = new ArrayList();
        arrayList.Add("ABC");
        arrayList.Add("AXY");
        arrayList.Add("PQR");

        // Accessing the first element
        var firstElement = arrayList[0];
        Console.WriteLine("First Element: " + firstElement);

        // Modifying the second element
        arrayList[1] = "Hello";
        Console.WriteLine("Modified Second Element: " + arrayList[1]);
    }
}

When the above code is compiled and executed, it produces the following result −

First Element: ABC
Modified Second Element: Hello

Iterating Through an ArrayList

You can iterate through an ArrayList using either a foreach loop or a for loop to access each element.

Example

This example demonstrates how to iterate through an ArrayList:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arrayList = new ArrayList() {"Prakash", "Krishna", "Sudhir"};

        Console.WriteLine("Using foreach loop:");
        foreach (var item in arrayList)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("\nUsing for loop:");
        for (int i = 0; i < arrayList.Count; i++)
        {
            Console.WriteLine(arrayList[i]);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Using foreach loop:
Prakash
Krishna
Sudhir

Using for loop:
Prakash
Krishna
Sudhir

Sorting an ArrayList

Elements of an ArrayList can be sorted in ascending order by using the Sort() method.

Example

This example demonstrates how to sort numeric values stored in an ArrayList:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList numbers = new ArrayList() { 5, 3, 8, 1 };
        numbers.Sort();

        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

1
3
5
8

Converting ArrayList to Array

You can convert an ArrayList to an array using the ToArray() method.

Example

This example demonstrates how to convert an ArrayList to an array:

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList arrayList = new ArrayList() {"Prakash", "Krishna", "Sudhir"};
        object[] array = arrayList.ToArray();

        Console.WriteLine("Array Elements:");
        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Array Elements:
Prakash
Krishna
Sudhir

Properties of ArrayList

The following table lists shows some of the commonly used properties of the ArrayList

Sr.No. Property & Description
1

Capacity

Gets or sets the number of elements that the ArrayList can contain.

2

Count

Gets the number of elements actually contained in the ArrayList.

3

IsFixedSize

Gets a value indicating whether the ArrayList has a fixed size.

4

IsReadOnly

Gets a value indicating whether the ArrayList is read-only.

5

Item

Gets or sets the element at the specified index.

Methods of the ArrayList Class

The following table lists shows some of the commonly used methods of the ArrayList

Sr.No. Method & Description
1 Add(object value)

Adds an object to the end of the ArrayList.

2 AddRange(ICollection c)

Adds the elements of an ICollection to the end of the ArrayList.

3 BinarySearch(Object)

Searches the entire sorted ArrayList for an element using the default comparer.

4 public virtual void Clear()

Removes all elements from the ArrayList.

5 Clone();

Creates a shallow copy of the ArrayList.

6 Contains(object item)

Determines whether an element is in the ArrayList.

7 CopyTo(Array)

Copies the entire ArrayList to a compatible one-dimensional Array, starting at the beginning of the target array.

8 IndexOf(object)

Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.

9 Insert(int index, object value)

Inserts an element into the ArrayList at the specified index.

10 GetRange(int index, int count)

Returns an ArrayList which represents a subset of the elements in the source ArrayList.

11 Remove(object obj)

Removes the first occurrence of a specific object from the ArrayList.

12 RemoveAt(int index)

Removes the element at the specified index of the ArrayList.

13 RemoveRange(int index, int count)

Removes a range of elements from the ArrayList.

14 Reverse()

Reverses the order of the elements in the ArrayList.

15 Sort()

Sorts the elements in the ArrayList.

16 FixedSize(ArrayList)

Returns an ArrayList wrapper with a fixed size.

17 Synchronized(ArrayList)

Returns an ArrayList wrapper that is synchronized (thread-safe).

18 ToArray()

Copies the elements of the ArrayList to a new object array.

19 TrimToSize()

Sets the capacity to the actual number of elements in the ArrayList.

20 ReadOnly(ArrayList)

Returns a read-only ArrayList wrapper.

csharp_collections.htm
Advertisements