ArrayList in C Sharp

Introduction to the ArrayList Data Type

The traditional array still has many applications in software development and is supported by all mainstream languages. The ArrayList data type offers additional capabilities that make it much more attractive. In this tutorial we examine basic applications of the ArrayList data type in C Sharp (C#). We discuss the differences between a traditional array and an ArrayList and we present several examples.

In this tutorial we will discuss several important aspects of using ArrayList data items in software engineering: declaration, instantiation, adding, clearing, sorting, and traversing. We provide examples in code and also a complete working program that combines all the concepts that have been introduced.

Motivation

Software engineers and system architects must be conversant with modern data structures available in modern development environments. Certainly, traditional arrays could be used to solve programming problems. However, ArrayList data items often result in more productive programmers. Memory management issues and concomitant logic errors can be avoided by using tools that have been thoroughly debugged and widely accepted. Code written using standardized data structures, such as ArrayLists, is more easily understood by other software professionals, resulting in code that is more maintainable.

It is the responsibility of programmers and analysts to recognize opportunities to leverage the features and capabilities of modern software development environments. When studying an algorithm, several data structures may be applicable, but some data structures may be more advantageous than others.

Preparing to use the ArrayList in a class

In order to have access to the ArrayList class in a C# program, a using directive must be added to the code:

using System.Collections;       // ArrayList definition

This directive instructs the compiler to include a namespace called Collections, which formally defines the class ArrayList. Many other classes are also in the Collections namespace: they are not addressed in this tutorial but they are significant and should be studied by software development professionals.

Declaring an ArrayList data item

Declaration of an ArrayList data item can be accomplished in one or two lines of code. We first consider the 2-line implementation:

ArrayList foo;		// Declare
foo = new ArrayList();	// Instantiate

This simple two-line example breaks down the process of declaring and instantiating an ArrayList data item into 2 separate lines of code. The first line declares an object of type ArrayList, called foo. The second line allocates memory space for the ArrayList data item and stores the address of that space in foo.

It is interesting to study this code in a little more detail. The first line is not strictly an executable statement: it simply adds an entry to the symbol table, associating the symbol foo with the data type ArrayList. The second line requires heap space to be allocated, which happens as the finished program is executing.

These two lines of code could easily be combined into one:

ArrayList foo = new ArrayList();

Either style is acceptable: they both have the same effect. The second option is slightly more compact and combines declaration with instantiation. One significant difference between the two styles is the ability to optionally include additional statements between the declaration and the instantiation steps. In many cases it is advantageous to postpone the instantiation based on other decisions of calculations that must be performed at run time. Since the instantiation step does consume memory, which is a limited resource, programmers should carefully consider how and when instantiations are executed.

This probably is not a good idea

Combining the two styles described above may result in inefficient code. The following example illustrates a bit of logic that is syntactically correct but logically suspect.

ArrayList foo = new ArrayList();
foo = new ArrayList();

Note that the first line performs the declaration and instantiation steps, which is proper, but the second line immediately instantiates another ArrayList object and assigns the reference to foo all over again. The second instantiation causes the first instantiation go out of scope: that object is deallocated and no longer available to the program.

Adding elements to the ArrayList object

The ArrayList class, as declared and instantiated in the previous examples, contains no data. Adding an element is straightforward:

foo.Add(42);   // Add an element to the ArrayList object

Our ArrayList object now contains one element, which is an integer with the value 42. When the method was called, memory was allocated to contain the integer and that space was initialized to 42. Memory management is the responsibility of the class and the operating system.

The ArrayList class provides methods and properties that make data manipulation very convenient. We will touch on a few of the popular properties and methods here. The following line of code demonstrates how to use the count property. Aptly named, this property tracks the number of elements currently stored in the object. It is updated dynamically as elements are added and removed

Console.WriteLine("foo now has " + foo.Count + " items");

Loosely typed ArrayList elements

Another significant advantage of ArrayList objects over traditional arrays is the ability to build lists of objects with disparate types. The following code illustrates this concept:

foo.Add("Peach");   // Add a string element
foo.Add("Plum");    // Add a string element
foo.Add(99.9);      // Add a double element

After executing the above code, our object contains one integer, two strings, and one double.

We can easily write code to traverse the object and access the elements one-by-one:

// Traverse the ArrayList object
for (int i = 0; i < foo.Count; i++)
{
	Console.WriteLine(i + ": " + foo[i]);
}

A basic for loop illustrates the syntax for accessing individual elements of the ArrayList object: we use traditional notation. Note that indexing begins at zero and proceeds to (foo.count - 1). There is no foo[foo.count]: attempting to access it will throw an exception.

Clearing the ArrayList

A call to the Clear method causes the ArrayList object to erase any elements currently stored in it. The elements are no longer available to the program and the Count property has the value 0. The operating system and the ArrayList class are responsible for memory management.

foo.Clear();	// Erase all the elements in the ArrayList

Sorting the ArrayList

The ArrayList class includes a sorting algorithm. An example is illustrated below:

foo.Sort();
Output of the final program.
Output of the final program.

The implementation of the sort algorithm is not immediately obvious and is generally not relevant to programmers who use the ArrayList class in their code. Technical documentation suggests that the sort is programmed as a QuickSort algorithm, but users of the ArrayList class have no control over such details.

Note that the Sort algorithm depends on a proper implementation of the IComparable interface, which is beyond the scope of this tutorial. This interface is provided for some data types such as ints and strings. In other words, sorting an ArrayList object containing non-homogeneous types may result in a program exception unless the appropriate IComparable interface(s) have been provided.

/*
 * ArrayList demonstration
 * (c) nicomp
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;       // ArrayList definition

namespace Project1
{
    class main
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Using the ArrayList in C#");

            ArrayList foo;          // Declaration
            foo = new ArrayList();  // Instantiation

            foo.Add(42);            // Add an element to the ArrayList object

            Console.WriteLine("The ArrayList object now has " + foo.Count + " items");

            foo.Add("Peach");   // Add a string element
            foo.Add("Plum");    // Add a string element
            foo.Add(99.9);      // Add a double element

            // Traverse the ArrayList object
            for (int i = 0; i < foo.Count; i++)
            {
                Console.WriteLine(i + ": " + foo[i]);
            }

            foo.Clear();
            Console.WriteLine("The ArrayList object now has " + foo.Count + " items");

            // Put a few more ints into the object
            foo.Add(100); foo.Add(1); foo.Add(-1); foo.Add(0);
            foo.Sort();
            // Traverse the ArrayList object after sorting it
            Console.WriteLine("After sorting...");
            for (int i = 0; i < foo.Count; i++)
            {
                Console.WriteLine(i + ": " + foo[i]);
            }

        }


    }
}

More by this Author


Comments 2 comments

Princess 5 years ago

very nice its really help me out


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@Princess : Thanks!

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working