ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ArrayList in C Sharp

Updated on July 19, 2011

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]);
            }

        }


    }
}
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)