Pages

Men

rh

6/16/2012

Non Generic Collections in C#

Non Generic Collections:
  • Array List
  • Hash Table
  • Stack
  • Queue
Array List:
 Array List is one of the types of Collections. Using Array List can add different data types of elements. The size of the array list automatically increases when we add items to the array list. Array List implements the IList interface using array whose size is dynamically increased as required.
Array List available in System.Collections name space.

Advantages:
  • Array List automatic resizing capability.
  • Convenient to use.
  • Array list has methods to Add, Insert and Remove range of elements.
  • Easy to create Thread safe Array List  using Synchronized method
Disadvantages:
  • Array list does not sort the elements automatically. User need to sort the array list using arraylist.sort () method.
  • The capacity of a ArrayList is the number of elements the ArrayList can hold. As elements are added to a ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.
  • Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
  • ArrayList accepts a null reference (Nothing in Visual Basic) as a valid value and allows duplicate elements.
 Example:
 Class Program
    {
        static void Main (string [] args)
        {
            ArrayList dataArray = new ArrayList();

            for (int i = 0; i < 20; i++)
            {
                dataArray.Add(i);
            }
            // or you can add any object type like below.
            dataArray.Add ("Object type");
        }
    }
Dictionary :

  • Dictionaries are very sophisticated data structures that allow us to access an element based on some key, which can be of any type.
  • Dictionaries are in dotnet represented by class Hash Table. Hash Table can store whatever data structure you want.
  • Hashtable is one of the collection type which can be use to store elements based on key.
Hash Table ht = new Hashtable ();

Why Hash Table:          
Suppose you have some data, which needs to be stored in two dimensional arrays and have a link format of Key and Value. For example, a person name and his social security number and we can access their data using a key.

 Disadvantages:

  • Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be Nothing, but a value can be.
  • Key objects must be immutable as long as they are used as keys in the Hashtable.
  • When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.
  • As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.
  • Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.
  • The capacity of a Hashtable is the number of elements the Hashtable can hold. As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.
Example
                  Hashtable  openWith = new Hashtable();
                   // Add some elements to the hash table. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
 
IList
            Represents a collection of objects that can be individually accessed by index.

Disadvantages:
  • IList is a descendant of the ICollection interface and is the base interface of all lists.
  • IList implementations fall into three categories: read-only, fixed-size, variable-size. A read-only IList cannot be modified. A fixed-size IList does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size IList allows the addition, removal and modification of elements.
Example:
               class w3example 
               { 
                       static oid Main(string[] args) 
                       { 
                           // create a new list 
                           IList<string> list = new List<string>() ; 
                           // add new items with the Add method 
                           list.Add("item1") ; 
            list.Add("item2"); 
            list.Add("item3"); 
 
            // use the indexer to set the third value 
            list[ 2] = "item3changed"; 
 
            // insert an item at the head of the list 
            list.Insert(0, "item0"); 
                                                                                            // remove an item 
            list.RemoveAt(2); 
 
            // enumerate the items in the list 
            foreach (string str in list)
                { 
                         Console.WriteLine("List item: {0}", str); 
                                  } 
                           // check for items in the list 
            Console.WriteLine("Index of {0}: {1}", "item1",  
            list.IndexOf("item1") ); 
            Console.WriteLine("Index of {0}: {1}", "item2",  
            list.IndexOf("item2") ); 
           // wait for input before exiting 
            Console.WriteLine("Press enter to finish"); 
            Console.ReadLine(); 
                    } 
           }  
 
ICollections:
Defines size, enumerators and synchronization methods for all collections.

Disadvantages:
  • The ICollection interface is the base interface for classes in the System.Collections namespace.
  • IDictionary and IList are more specialized interfaces that are based on the ICollection interface. An IDictionaryimplementation is a collection of key-and-value pairs, like the Hashtable class. An IList implementation is a collection of values that can be sorted and whose members can be accessed by index, like the ArrayList class.
  • Some collections that limit access to their elements, like the Queue class and the Stack class, directly implement the ICollection interface.
  • If neither the IDictionary interface nor the IList interface meet the requirements of the required collection, derive the new collection class from the ICollection interface instead for more flexibility.
IDictionary:
Represents a collection of key-and-value pairs.

Disadvantages:
  • The IDictionary class is the base interface for collections of key-and-value pairs.
  • Each element is a key-and-value pair stored in a Dictionary Entry object.
  • Each association must have a unique key that is not a null reference (Nothing in Visual Basic), but the value of an association can be any object reference, including a null reference (Nothing).
  • The IDictionary interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order.
  • IDictionary implementations fall into three categories: read-only, fixed-size, variable-size. A read-only IDictionary
  • cannot be modified. A fixed-size IDictionary does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size IDictionary allows the addition, removal and modification of elements.

No comments :

Post a Comment