Array, Arraylist, Hashtable, DataDicitonary in C#
Difference between Hash table and Data Dictionary in
C#
- HashTable & Dictionary,Dictionary is generic whereas Hastable is not Generic.
- · We can add any type of object to HashTable ,but while reteriving we need to Cast it to the required Type.So it is not type safe.But to dictionary,while declaring itself we can specify the type of Key & Value ,so no need to cast while retreiving.
HashTable Program:
Hashtable ht = new Hashtable();
ht.Add(1,"One");
ht.Add(2,"Two");
ht.Add(3,"Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine( Key + " " + value);
}
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int,string> dt = new Dictionary<int,string>();
dt.Add(1,"One");
dt.Add (2,"Two");
dt.Add (3,"Three");
foreach (KeyValuePair<int,String> kv in dt)
{
Console.WriteLine( kv.Key + " " + kv.Value);
}
}
}
Difference between Hashtable and ArrayList in C#
- A hashtable store data as key, value pair. While an ArrayList only value is store.
- · If you want to access value from the hashtable, you need to pass name. While in arraylist to access value, you need to pass index value.
- Hence the basic difference is that HashTable represents a collection of key/value pairs that are organized based on the hash code of the key.
- The ArrayList class implements a collection of objects using an array whose size is dynamically increased as required.
Hashtable
Hashtable ht = new Hashtable();
ht.Add("01", "Rk Singh");
ht.Add("02", "Kunal");
ht.Add("03", "Prashant");
ht.Add("04", "Mohan");
ht.Add("05", "Satya");
ICollection key = ht.Keys;
foreach (string k in key)
{
Response.Write(k + ": " + ht[k]);
}
Array list
ArrayList al = new ArrayList();
al.Add(11);
al.Add(42);
al.Add(33);
al.Add(21);
al.Add(35);
al.Add(46);
al.Add(77);
foreach (int i in al)
{
Response.Write(i + " ");}
Difference between Array and ArrayList in C#
Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.
string[] arr=new string[2];
arr[0] = "welcome";
arr[1] = "yyyy";
ArrayList strarr = new ArrayList();
strarr.Add("welcome"); // Add string values
strarr.Add(10); // Add integer values
strarr.Add(10.05); // Add float values
|
Arrays
|
ArrayLists
|
|
These are strong type collection and allow
to store fixed length
|
Array Lists are not strong type collection
and size will increase or decrease dynamically
|
|
In arrays we can store only one datatype
either int, string, char etc…
|
In arraylist we can store all the datatype
values
|
|
Arrays belong to System.Array namespace
|
Arraylist belongs to System.Collection
namespace
|
Comments
Post a Comment