Topic : CSharp Collection - Hashtable Class in C# Programming Language:

Hashtable:

C# Includes Hashtable collection in System.Collections namespace, which is similar to Generic Dictionary Collection. The Hashtable collection stores key-value pairs. It Optimizes lookups by computing the hast code of each key and stores it in a different bucket internally and then matches the hash code of the specifies key at the time of accessing values.




Hashtable : infobrother

A Hashtable is used when we need to access elements by using Key, and we can identify a useful key value. Each Item in the Hashtable has a Key-Value pair. The Key is used to access the items in the collection.

Hashtable Class provides some useful methods and properties to work with hash table collection. The following table lists some of the commonly used Properties of the Hashtable Class.



PropertiesDescription
CountGets the number of key/value pairs contained in the Hashtable.
IsFixedSizeGets a value indicating whether the Hashtable has a fixed size.
IsReadOnlyGets a value indicating whether the Hashtable is read-only.
itemGets or sets the value associated with the specified key.
KeysGets an Collection containing the keys in the Hashtable.
ValuesGets an Collection containing the values in the Hashtable.


The following table lists some of the commonly used Methods of the Hashtable Class.

MethodsDescription
Add()Adds an element with the specified key and value into the Hashtable.
Clear()Removes all elements from the Hashtable.
Contains()Determines whether the Hashtable contains a specific key.
ContainsKey()Determines whether the Hashtable contains a specific key.
ContainsValue()Determines whether the Hashtable contains a specific value.
Equals()Determines whether the specified object is equal to the current object
KeyEquals()Compares a specific Object with a specific key in the Hashtable.
Remove()Removes the element with the specified key from 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.

The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. The default load factor of 1.0 generally provides the best balance between speed and size. A different load factor can also be specified when the Hashtable is created. 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.



capacity:

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.



Let's have an Example to clear the concept of Hashtable. We will Write a code to add some elements in the hash table Collection. will retrieve the element, update elements and remove elements from particular location. we'll try to cover most of the properties and methods of Hashtable class.



/*Example - hashtable Class - InfoBrother*/

using System;
using System.Collections;

class Example
{
    public static void Main()
    {
        // Create a new hash table.
        Hashtable Code = new Hashtable();

        /* Add some elements to the hash table. We can't add duplicate key:
           but some of the values could be duplicates. */
        Code.Add(992, "Pakistan");
        Code.Add(968, "Oman");
        Code.Add(971, "UAE");
        Code.Add(670, "Saipan");

        /* The Add method throws an exception if the new key is 
           already in the hash table. */

        try
        {
            Code.Add(992, "Romania");
        }
        catch
        {
            Console.WriteLine("An element with Key = \"992\" already exists.");
        }


        /* The Item property is the default property, so we 
           can omit its name when accessing elements.  */
        Console.WriteLine("For key = \"992\", value = {0}.", Code[992]);

        /* The default Item property can be used to change the value
            associated with a key. */
        Code[971] = "Emirates";
        Console.WriteLine("For key = \"971\", value = {0}.", Code[971]);

        /* If a key does not exist, setting the default Item property
            for that key adds a new key/value pair. */
        Code[974] = "Qatar";

        // ContainsKey can be used to test keys before inserting them.
        if (!Code.ContainsKey(65))
        {
            Code.Add(65, "Singapore");
            Console.WriteLine("Value added for key = \"65\": {0}", Code[65]);
        }

        /* When you use foreach to enumerate hash table elements,
           the elements are retrieved as KeyValuePair objects. */
        Console.WriteLine();
        foreach (DictionaryEntry de in Code)
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }

        // To get the values alone, use the Values property.
        ICollection valueColl = Code.Values;

        /* The elements of the ValueCollection are strongly typed
           with the type that was specified for hash table values. */
        Console.WriteLine();
        foreach (string s in valueColl)
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        ICollection keyColl = Code.Keys;

        /* The elements of the KeyCollection are strongly typed
           with the type that was specified for hash table keys. */
        Console.WriteLine();
        foreach (int s in keyColl)
        {
            Console.WriteLine("Key = {0}", s);
        }


        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove \"Saipan\" From List: ");
        Code.Remove(670);

        if (!Code.ContainsKey(670))
        {
            Console.WriteLine("Key \"670\" Saipan not found.");
        }

        Console.ReadKey();
    }
}



Hashtable is a non-generic collection so it can contain a key and a value of any data type. So, values must be cast to an appropriate data type otherwise it will give compile-time error.



Different Between Array & ArrayList:

» Hashtable included in System.Collections namespace.

» Hashtable is loosely typed (non-generic) collection, this means it stores key-value pairs of any data types.

» Hashtable is thread safe.

» Hashtable returns/throws Exception if we try to find a key which does not exist.

» Data retrieval is slower than dictionary because of boxing-unboxing.

» Read More About Hashtable...

» Dictionary included in System.Collections.Generic namespace.

» Dictionary is generic collection. So it can store key-value pairs of specific data types.

» Only public static members are thread safe in Dictionary.

» Dictionary returns null if we try to find a key which does not exist.

» Data retrieval is faster than Hashtable.

» Read More About Dictionary...



For complete list of properties and methods, please visit Microsoft's C# documentation.
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement