Showing posts with label Difference between Arraylist and Generic List. Show all posts
Showing posts with label Difference between Arraylist and Generic List. Show all posts

Thursday, December 23, 2010

Difference between Arraylist and Generic List


Difference between Arraylist and Generic List

private void button1_Click
(object sender, EventArgs e)
{
//Arraylist - Arraylist accept values as object
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object

Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing

//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.

String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>

//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List strLst = new List();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");

List intLst = new List();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);

List decLst = new List();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);

List empLst = new List();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));


//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];
}