Difference between ArrayList and List

Posted by VIJI Friday, July 3, 2009

In this article we can see the difference between ArrayList and List


In Arraylist - we can store different data types.
In List we can store data of specific type.

Arraylist - not type safety
List - type safety

Boxing and UnBoxing

Arraylist accept values as object. We can store any type of data such as string, integer, decimal etc. This is known as Boxing

To retrieve the vales from arraylist we have to specify the index.
and it will return that values as object.

we have to explcitly typecast that value from object to its original type.

This is known as Unboxing. While typecasting we need to know the type of the data to be converted into.

So in Arraylist - will face issues Like Boxing and unboxing


But in List (Generics) we can specify the type of data we are going to insert in to
List. So that we can avoid boxing and unboxing

No boxing and Unboxing so that generics are type safety .

Example

[CODE]
//Storing in ArrayList
//Explains Boxing and Unboxing Concept

Class Employee
{
String empId;
String empName;

};

Employee emp = new Employee("EMP001", "Viji");

ArrayList arr = new ArrayList();
arr.Add("Viji");
arr.Add(123);
arr.Add(45.123);
arr.Add(emp);
//This process is known as boxing

//To retrieve the 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];
//This process that is converting from object to its original type is known as unboxing

[/CODE]


//List
// We have to specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing

//Example



List strLst = new List();
strLst.Add("Viji");//Here List accepting values as String only
strLst.Add("Raj");

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

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

Class Employee
{
String empId;
String empName;

};

List empLst = new List();
empLst.Add(new Employee("1", "Viji"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Raj"));


//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];

0 Responses to Difference between ArrayList and List

Post a Comment