Working with Collections - ArrayList

SheoNarayan
Posted by in C# category on for Intermediate level | Views : 28436 red flag
Rating: 4.5 out of 5  
 2 vote(s)

This article describes about ArrayList, its various methods and uses. ArrayList is a simple and resizable index-based collections of objects. This is a kind of array that is capable of increase its size dynamically.
Introduction

In series of next few articles, I am planning to write about collections. Collections are a place to store similar or different types of data in an orderly manner. .NET Framework provide different type of collections for use at different places. Collections classes are the base of application development because of the utility they provide to the developer.

There are several types of collections in .NET and all these collections classes resides in System.Collections namespace. 

This article describes about ArrayList (Read article on List, Generic equivalent of ArrayList http://www.dotnetfunda.com/articles/article152.aspx) and where it best fits. ArrayList is a simple and resizable index-based collections of objects. This is nothing but a kind of array that is capable of increase its size dynamically. It can store any kind of data that inherit from System.Object (In .NET all data types are inherited from System.Object so virtually you can store any type of data into any collections.) ArrayList still uses array type to implement most of its functionality. ArrayList best fits in the scenario where you don't know what is the exact size of the items you are going to add in the collections, want to store variable data irrespective of the data types and your collections are relatively small or medium size.


Adding items to the ArrayList

Add Method

ArrayList supports two methods of adding items to the collections and these are Add and AddRange. Add method is used to store any kind of data into the collections, it can either be string, numeric or any custom objects.

// ArrayList

ArrayList arrayList = new ArrayList();

string lastName = "Narayan";

arrayList.Add("Sheo");

arrayList.Add(lastName);

arrayList.Add(31);

arrayList.Add(new object()); 

Here you can see that I have added variable, string, numeric or simple object into the collections. In order to add object into an ArrayList, its not necessary to be of the same type.

AddRange Method

In addition to Add method, ArrayList also supports AddRange method that is used to add more than an item into the collection at one go. This is done usually from either an Array or another collections.

// ArrayList AddRange method

string[] items = new string[] { "Sheo", "Narayan", "Hyderabad", India" };

arrayList.AddRange(items);

AddRange supports adding a range of items from any collections that support ICollection interface (Infact most of the collections object supports this interface).

Insert and InsertRange method

One important thing to notice here is that Add and ArrayList add items into the collection at the end of it, what if you want to insert the items in the mid of the collection or at any specific postions? To do that ArrayList supports Insert and InsertRange methods. These methods works in the same way as Add and AddRange do but one more parameter you need to pass into these methods is the postion at which you want to insert the item.

// ArrayList - Insert method

arrayList.Insert(3, "Dutta");

// ArrayList - InsertRange method

int[] insertItems = new int[] { 9, 10, 11 };

arrayList.InsertRange(7, insertItems);

Overwriting an item

If you want to overrite an item already in the ArrayList, you can use the indexers to do that.

// ArraList - Indexers to overwrite item

arrayList[5] = "Overwrite item";

Removing items from ArrayList

The way we added the items into the ArrayList, we can remove the items from ArrayList using Remove and RemoveRange methods. One additional method is provided by ArrayList to remove an item is RemoteAt. Lets see them one by one

Remove Method

Remove method is used to remove a item from the collections. But notice that if you are trying to remove an item that doesn't exist into the collections, ArrayList will not throw any error, this is cool, isn't it?.

// ArrayList - Remove method

arrayList.Remove(31);

// ArrayList - Remove method, this will not throw any error even if this item doesn't exist in the collection

arrayList.Remove("Unknown Item");

RemoveAt Method

In case you need to remove an item from a specific location from the ArrayList, you can use RemoveAt method. In the following example, 4 item from the ArrayList will be removed.

// ArrayList - RemoveAt method

arrayList.RemoveAt(4);

RemoveRange Method

If you want to remove more than one item from the ArrayList at one go, simply use the RemoveRange method. In this method you need to specify from which index you want to start with and how many items you want to remove. In following example 6th, 7th, and 8th item will be removed from the ArrayList as I have specified first parameter from where to start removing item is 5 (Actually it will be 6th item as collections are 0 based index and its counting starts from 0) and from there 3 items will be removed.

// ArrayList - RemoveRange method

arrayList.RemoveRange(5, 3);

// Demo of RemoveRange

ArrayList myArrayList = new ArrayList(0);

int[] myInt = new int[] {1, 2, 3, 4, 5};

myArrayList.AddRange(myInt);

// ArrayList - RemoveRange method

myArrayList.RemoveRange(1, 3);

string str = string.Empty;

foreach (int i in myArrayList)

{

str += i.ToString() + " :";

}

The output of above code will be 1, 5. As the first parameter is 1, it means the 2nd item ie. 2, and remove 3 items from there ie. 2, 3, 4.

Iterating through items


You must be agree that if we will not have any option to iterate through the items of the collections and get it back, it will be of hardly any use. ArrayList also provids way to iterate through the items of the collections and there are many ways to do that.

Using Indexers

ArrayList has a Count property that tells us the size of the collections, we can use them to loop through the ArryaList.

string str = string.Empty;

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

{

str += myArrayList[i].ToString() + " :";

}

Using Enumerators

ArrayList also supports IEnumerable interface that allows us to use enumerators to access the items of the collections.

string str = string.Empty;

IEnumerator enm = myArrayList.GetEnumerator();

while (enm.MoveNext())

{

str += enm.Current.ToString() + " :";

}

Using ForEach loop

ForEach loop is just like enumerators, actually internally it use Enumerators to enumerate through all the items in the collections. The benefit of using ForEach loop is you can specify the the data type while looping through the items that saves time in casting from objects while looping.

// Specifying the data type
foreach (int i in myArrayList)

{

str += i.ToString() + " :";

}

// Generic - it will work for all types of object stored in the ArrayList

foreach (object obj in myArrayList)

{

str += obj.ToString() + " :";

}

Sorting an ArrayList


ArrayList also supports sorting of the item. To sort the item simply call the Sort method. This method also takes IComparer object as parameter if you want to use case insensitive sorting or you want to specify your own comparer class to compare and sort.

// ArrayList - Sort method

arrayList.Sort();

// ArrayList - Sorting, Case insensitive comparsion and sorting

myArrayList.Sort(new CaseInsensitiveComparer());

There are few more methods that are frequently used while working with ArrayList. These are:

Other Important Methods

Clear Method
Clear method is used to clear all the item from the collections.

myArrayList.Clear();

IndexOf Method

IndexOf method is used to determine if a particular item exists in a collections or not. If an item exists then it will return the 0 based index of that item otherwise -1.

// will return 1

myArrayList.IndexOf(5);

// Will return -1 as I have removed 2, 3, 4 has been removed from the list

myArrayList.IndexOf(3);


Hope this article will be useful for beginners as well as mid level developers. Please let me know if you have comments or suggestions. Thanks for reading.
Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)