Today I will explain what is the difference between ArrayList and List?
ArrayList
|
List
|
Syntax:
ArrayList Arr =
new ArrayList();
Arr.Add(123);
Arr.Add(“Dev”);
Arr.Add(‘C’);
|
Syntax:
List<int>
Lst = new List<int>();
Lst.Items.Add(1);
Lst.Items.Add(2);
Lst.Items.Add(3);
|
ArrayList belongs
to System.Collection namespace.
You need to import
System.Collection namespace to your class files with using keyword.
Using System.Collections;
|
List belongs to System.Collections.Generic namespace.
You need to import
System.Collection.Generics namespace to your class files with using keyword.
Using System.Collections.Generics;
|
ArrayList is not strongly
typed.
For better
understand it does not have type restriction.
Ex.
ArrayList Arr =
new ArrayList();
Arr.Add(123);
Arr.Add(“C”);
Arr.Add(“Devendra
Gohel”);
So you can store
anything in arraylist it’s not matter what types of data inserted.
|
List is strongly typed.
Ex.
List<int>
Lst = new List<int>();
Lst.Add(1);
Lst.Add(2);
Lst.Add(“Devendra”);//
throw error.
So you cannot
store anything to the list because it’s already defined which data type is
going to stored. In this we already defined int data type so now list allowed
only numeric fields.
|
ArrayList stored
all data as object thus when we need to get back those data we must remember
what you stored.
int number =
Convert.ToInt32(Arr[0]);
char charn = Convert.ToChar(Arr[1]);
string str =
Arr[2].ToString();
|
List is stored
defined data types so we need not to worry about it.
|
Arraylist using
loop you need to use object data type.
Ex.
Foreach(Object
data in Arr)
{
Console.WriteLine(data);
}
|
You can iterate
over Generic using list already defined data type.
Ex.
Foreach(int data
in Lst)
{
Console.WriteLine(data);
}
|
Download Power point presentation:
Difference between ArrayList and List
No comments:
Post a Comment