In this article we will discuss about Arraylist, Hash table, Sorted list and Dictionary.
Arraylist:
- This is one type of Array whose size can increase and decrease dynamically.
- Arraylist can hold items of different types.
- The base class is System.Collections.ArrrayList.
- An ArrayList uses an array internally and initializes its size with a default value called capacity. As the no of elements increases or decreases , it adjust the capacity of the array by making a new array and copying the old values into it.
ArrayList list = new ArrayList();
To add elements in ArrayList
list.add("Raju");
list.add("biju");
To remove the element from the arraylist
list.Remove("raju");
To remove the element at index 1
list.Remove(1);
To remove three elements starting at index 4
list.RemoveRange(4,3);
Hash table:
- Hash table provides a way of accessing the index using a user identified key value.
- It removes the index problem.
- It stores the items as key value pairs.Each item(value) in the hash table is uniquely identified by its key and its value as an object type.
- Mostly string class is used as the key in hash table but we can also use other class as key.
Hashtable myht = new Hashtable();
myht.Add("one","The");
myht.Add("two","quick");
Here 'two' and 'one' are the keys and 'The' and 'quick' are the values.
PrintKeysAndValues(myht);
To remove elements with the key "two"
myht.Remove("two");
Sorted list:
Simillar to Hash table, the difference is that the values are sorted by keys and acessible by key as well as by index.
SortedList mysl = new SortedList();
mysl.Add("one","The");
mysl.Add("two","quick");
Dictionary:
- A kind of collection that stores items in a key-value pair fashion.
- Each value in the collection is identified by its key.
- All the keys in the collection are unique and there cannot be more than one key with the same name.
- The most common types of dictionary in the system.collection name space are Hash table and the sorted list.
There are following difference between ArrayList and Hashtable :-
ReplyDeleteA hashtable store data as name, 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.
In a hastable you can store different type of data like int, string etc. While in arraylist you can store only similar type of data.
For more please visit http://www.etechpulse.com/2013/08/what-is-difference-between-arraylist.html
Thanks
More ...C# Interview Questions and answers
ReplyDeleteLing