Monday, September 20, 2010

System.Collections ( Array List )

ArrayList

The ArrayList class is a dynamic array of heterogeneous objects. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only.

We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object type.

An ArrayList uses its indexes to refer to a particular object stored in its collection.

The Count property gives the total number of items stored in the ArrayList object.

The Capacity property gets or sets the number of items that the ArrayList object can contain.

Objects are added using the Add() method of the ArrayList and removed using its Remove() method.

( heterogeneous - Consisting of elements that are not of the same kind )

An example of usage of an ArrayList is given below.

int a =4;

double b =5.6;

ArrayList ObjArrLst = new ArrayList();

ObjArrLst.Add("Cricket");

ObjArrLst.Add(a);

ObjArrLst.Add(b);

It is to be noted here that the initial capacity of an ArrayList is 16, which is increased once the 17th item is stored onto it. This repeated memory allocation and copying of the items can be quite expensive in some situations.

For performance reasons we can set the initial capacity of the object of an ArrayList by using the Capacity property of the ArrayList class. This is shown in the example below.

int a =4;

double b =5.6;

ArrayList ObjArrLst = new ArrayList();

ObjArrLst.Capacity =3;

ObjArrLst.Add("Cricket");

ObjArrLst.Add(a);

ObjArrLst.Add(b);

Other methods available with Array List Class are

ClearRemoves all elements from the ArrayList.
Public methodCloneCreates a shallow copy of the ArrayList.
Public methodContainsDetermines whether an element is in the ArrayList.

InsertInserts an element into the ArrayList at the specified index.

RemoveRemoves the first occurrence of a specific object from the ArrayList.
Public methodRemoveAtRemoves the element at the specified index of the ArrayList.

ReverseReverses the order of the elements in the entire ArrayList.

SortSorts the elements in the entire ArrayList.

ToArrayCopies the elements of the ArrayList to a new Object array.

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.