Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C SHARP - HASH TABLE CODE




Example :



using System.Collections;

public class HashTableApplication {

    public static void Main(string[] args) {

        Hashtable hashtable = new Hashtable();

        hashtable.Add("ABA", 13);
        hashtable.Add("CAB", 12);
        hashtable.Add("BAC", 15);

        int i = (int)hashtable["ABA"];

        System.Console.WriteLine( "ABAs age is "+i);

        int j = (int)hashtable["BAC"];

        System.Console.WriteLine( "BACs age is "+j);
    }
}


Output :



  ABAs age is 13
  BACs age is 15

Code explanation for Hash Table


Luckily, C# already provides Hashtable defined in System.Collections.


All we have done is imported it and used it.


using System.Collections;

As we know we have stored the names ABA, CAB and BAC and their corresponding ages 13, 12 and 15 in the Hashtable.


hashtable.Add("ABA", 13);
hashtable.Add("CAB", 12);
hashtable.Add("BAC", 15);

But how they are stored in the HashTable will be decided by C#. As we are using the Hashtable provided by C#.


So, for ABA, a Hash Code is calculated by C# and the age of ABA is stored in some location decided by C#.


Similarly, the age of CAB and BAC is stored in the Hashtable after C# calculates the Hash Code, and decides where they will be stored.


Then we try to retrieve the age of ABA.


int i = (int)hashtable["ABA"];

So, we pass the name of ABA and internally C# calculates the Hash Code for ABA and gives us the age of ABA from the Hashtable.


And we print the age of ABA on the screen.


System.Console.WriteLine( "ABAs age is "+i);

Similarly we retrieve the age of BAC and print it on the screen.


int j = (int)hashtable.get("BAC");

System.Console.WriteLine( "BACs age is "+j);