Hashtable.md - brainchildservices/curriculum GitHub Wiki
Slide 1
Hashtable Class
- The Hashtable is a non-generic collection that stores key-value pairs.
- It uses the key to access the elements in the collection.
- It optimizes lookups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified * key at the time of accessing values.
- It is defined in the System.Collections namespace
- A Hashtable implements IDictionary interface.
- Keys must be unique and cannot be null.
- Values can be null or duplicate.
Slide 2
How to create a Hashtable?
We have to add using System.Collections to create a Hashtable.
Hashtable can be created using the new keyword and Hashtable class.
Hashtable HashTableName = new Hashtable();
using System;
using System.Collections; //Adding Collection Namespace for using Hashtable
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable(); //Declaring a new Hashtable
}
}
Slide 3
##How to Add elements to a Hashtable?
Items can be added to the Hashtable using the Add Method. The Add method has two parameters, a key and a value.
HashTableName.Add(Key, Value);
using System;
using System.Collections;
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "Aaron"); //The string value 'Aaron' is added to the Hashtable with the key value 1
myHT.Add("text", "Harry Porter"); //The string value 'Harry Porter' is added to the Hashtable with the key value 'text'
myHT.Add(2.34, 2546545); //The integer value '2546545' is added to the Hashtable with the key value 2.34
}
}
Slide 4
-
Key and Value can be any object.
-
Key cannot be duplicate : System.ArgumentException: Item has already been added
using System; using System.Collections; public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "Aaron"); myHT.Add("text", "Harry Porter"); myHT.Add(2.34, 2546545); myHT.Add(2.34, 456785); //The key 2.34 was already used to add an object to the Hashtable } }
Slide 5
-
Value can be duplicate
using System; using System.Collections; public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "Aaron"); myHT.Add("text", "Harry Porter"); myHT.Add(2.34, 2546545); myHT.Add("eBook", "Harry Porter"); //We have same value 'Harry Porter' for different key value 'text' and 'eBook' } }
Slide 6
How to count the number of elements in an Hashtable?
The number of elements in a Hashtable can be counted using the Hashtable.Count property.
Count: Gets the number of elements actually contained in the Hashtable.
using System;
using System.Collections;
public class Person
{
public string name;
public int age;
}
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "John");
myHT.Add(2, true);
myHT.Add('A', 1.2345);
myHT.Add('B', 20025);
Person P = new Person();
myHT.Add("myPerson", P);
Console.WriteLine("No of key-Value Pairs in the Hashtabke: " + myHT.Count);
myHT.Add('C', 20025);
Console.WriteLine("No of key-Value Pairs in the Hashtabke after adding one more Key-Value pair: " + myHT.Count);
}
}
Slide 7
How to count the number of elements in a Hashtable?
The number of elements in an Hashtablecan be counted using the Hashtable.Count property.
Count: Gets the number of elements actually contained in the Hashtable.
using System;
using System.Collections;
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "Aaron");
myHT.Add("text", "Harry Porter");
myHT.Add(2.34, 2546545);
myHT.Add("eBook", "Harry Porter");
Console.WriteLine("The number of elements in the Hashstable is: " + myHT.Count); //Using Count property to find the number of elements in HT
}
}
Slide 8
What elements can be stored to a Hashtable?
Hashtable.Add property allows us to add any object value and any object key to the Hashtable
using System;
using System.Collections;
public class Person
{
public string name;
public int age;
}
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "John"); //Storing a string value to the Hashtable at key value 1
myHT.Add(2, true); //Storing a boolean value to the Hashtable at key value 2
myHT.Add('A', 1.2345); //Storing a double value to the Hashtable at key value A
myHT.Add('B', 20025); //Storing a integer value to the Hashtable at key value B
Person P = new Person();
myHT.Add("myPerson", P); //Storing a Person object to the Hashtable at key value myPerson
}
}
Slide 9
How to access/read elements in a Hashtable?
-
Elements of the Hashtable can be accessed using the [] and the key value.
HashTableName[key];
using System; using System.Collections; public class Person { public string name; public int age; } public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "John"); myHT.Add(2, true); myHT.Add('A', 1.2345); myHT.Add('B', 20025); Person P = new Person(); myHT.Add("myPerson", P); Console.WriteLine("Element with key 1 is: " + myHT[1]); //Accessing the value using bracket[] and key value Console.WriteLine("Element with key B is: " + myHT['B']); Console.WriteLine("Element with key myPerson is: " + myHT["myPerson"]); } }
Slide 10
-
We can iterate through the Hashtable using the for each loop.
We would use the .Key and .Value property for that and using the DictionaryEntry objectusing System; using System.Collections; public class Person { public string name; public int age; } public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "John"); myHT.Add(2, true); myHT.Add('A', 1.2345); myHT.Add('B', 20025); Person P = new Person(); myHT.Add("myPerson", P); foreach(DictionaryEntry dicEntry in myHT) { Console.WriteLine("Key:"+dicEntry.Key+" Values: "+dicEntry.Value); } } }
Slide 11
*Iterate through all the values in Hashtable using the for each loop and ICollection of Keys.
Keys: Gets an ICollection containing the keys in the hash table.
Values: Gets an ICollection containing the values in the hash table.
using System;
using System.Collections;
public class Person
{
public string name;
public int age;
}
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "John");
myHT.Add(2, true);
myHT.Add('A', 1.2345);
myHT.Add('B', 20025);
Person P = new Person();
myHT.Add("myPerson", P);
ICollection keys = myHT.Keys; //Creates a collection of Key Values.
foreach (object key in keys) //Iterating through the keys collection and passing it as index to the Hashtable
{
Console.WriteLine("Values :" + myHT[key]);
}
}
}
Slide 12
How to change an element of the Hashtable?
We can change the element at specific index using the [] operator just like we do with arrays.
using System;
using System.Collections;
public class Person
{
public string name;
public int age;
}
public class Program
{
public static void Main()
{
Hashtable myHT = new Hashtable();
myHT.Add(1, "John");
myHT.Add(2, true);
myHT.Add('A', 1.2345);
myHT.Add('B', 20025);
Person P = new Person();
myHT.Add("myPerson", P);
Console.WriteLine("====================Original Hashtable============");
foreach(DictionaryEntry dicEntry in myHT)
{
Console.WriteLine("Key:"+dicEntry.Key+" Values: "+dicEntry.Value);
}
myHT[1]="Sebin"; //Changing the values at keys 1, A, 2
myHT['A'] = P;
myHT[2] = 123456;
Console.WriteLine("\n====================Modified Hashtable============");
foreach(DictionaryEntry dicEntry in myHT)
{
Console.WriteLine("Key:"+dicEntry.Key+" Values: "+dicEntry.Value);
}
}
}
Slide 13
How to remove an item from a Hashtable
You can remove an item or items from a Hashtable. The Hashtable class provides 2 methods to remove an item or items from it. These methods are:
- Remove
- Clear
Slide 14
-
Remove
The Remove() method has one parameter that is of object type. We need to pass a key to the Remove method which should be removed from the Hashtable. Remove(object)using System; using System.Collections; public class Person { public string name; public int age; } public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "John"); myHT.Add(2, true); myHT.Add('A', 1.2345); myHT.Add('B', 20025); Person P = new Person(); myHT.Add("myPerson", P); Console.WriteLine("====================Original Hashtable============"); foreach(DictionaryEntry dicEntry in myHT) { Console.WriteLine("Key:"+dicEntry.Key+" Values: "+dicEntry.Value); } myHT.Remove(1); //Removes key 1 that has John attached to it Console.WriteLine("\n====================Modified Hashtable============"); foreach(DictionaryEntry dicEntry in myHT) { Console.WriteLine("Key:"+dicEntry.Key+" Values: "+dicEntry.Value); } } }
Slide 15
-
Clear
The Clear method of Hashtable removes all the Key-Value pairs from the Hashtable.using System; using System.Collections; public class Person { public string name; public int age; } public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "John"); myHT.Add(2, true); myHT.Add('A', 1.2345); myHT.Add('B', 20025); Person P = new Person(); myHT.Add("myPerson", P); Console.WriteLine("====================Original Hashtable============"); foreach (DictionaryEntry dicEntry in myHT) { Console.WriteLine("Key:" + dicEntry.Key + " Values: " + dicEntry.Value); } myHT.Clear(); //Removes all the Key-Value pairs from the Hashtable Console.WriteLine("\n====================Modified Hashtable============"); foreach (DictionaryEntry dicEntry in myHT) { Console.WriteLine("Key:" + dicEntry.Key + " Values: " + dicEntry.Value); } } }
Slide 16
How to check the availability of key/value pair in hashtable?
In hashtable, you can check whether the given pair is present or not using the following methods:
-
Contains: This method is used to check whether the Hashtable contains a specific key.
-
ContainsKey: This method is also used to check whether the Hashtable contains a specific key.
-
ContainsValue: This method is used to check whether the Hashtable contains a specific value.
using System; using System.Collections; public class Person { public string name; public int age; } public class Program { public static void Main() { Hashtable myHT = new Hashtable(); myHT.Add(1, "John"); myHT.Add(2, true); myHT.Add('A', 1.2345); myHT.Add('B', 20025); Person P = new Person(); myHT.Add("myPerson", P); //Using Contains method to check if a specific Key exists in the Hashtable Console.WriteLine("Checking if Key 1 exisits using Contains method:"+myHT.Contains(1)); Console.WriteLine("Checking if Key 10 exisits using Contains method:"+myHT.Contains(10)); //Using ContainsKey method to check if a specific Key exists in the Hashtable Console.WriteLine("\nChecking if Key 1 exisits using ContainsKey method:"+myHT.ContainsKey(1)); Console.WriteLine("Checking if Key 10 exisits using ContainsKey method:"+myHT.ContainsKey(10)); //Using ContainsValue method to check if a specific Value exists in the Hashtable Console.WriteLine("\nChecking if Value John exisits using ContainsValue method:"+myHT.ContainsValue("John")); Console.WriteLine("Checking if Value Seban exisits using ContainsValue method:"+myHT.ContainsValue("Seban")); } }
Exercise
Create a hashtable to store 3 strings, 2 integers and 2 class objects of Employees.
Show all the keys of the Hashtable.
Show all the Values of the Hashtable using ICollection of Keys.
Show all the contents of the Hashtable using IDictionary.
Delete one string, 2 integers and 1 Employee object.
Show all the contents of the Hashtable using IDictionary.
Clear all contents of the Hashtable
Adding User-Defined objects to Hashtable
In this example, we are going to store a User-Defined class Student to the Hashtable.
The Student class has properties: Name, age and marks.
https://dotnetfiddle.net/WZhsgj
We create a Constructor for the Student class so that we pass values to the properties at the time of creation of Student objects.
https://dotnetfiddle.net/4XUvzK
In the Main method we create few instances of the Student class
https://dotnetfiddle.net/z5IGLW
Adding namespace System.Collections and creating a Hashtable, studHT to store Student objects.
https://dotnetfiddle.net/pkgfkn
Next we will add the student objects to the studHT Hashtable https://dotnetfiddle.net/oEYnWm
Option1: By TypeCasting
The Student objects in the ArrayList needs to be type casted to Student type.
((ClassName)Hashtable[index]).Memebers
https://dotnetfiddle.net/0QWYTg
This process of type casting allows us to access the members of the class.
https://dotnetfiddle.net/MEDAab
Now we can make a method GetData in Student Class with string return type in the Student class which uses the properties of the Class Student.
https://dotnetfiddle.net/D3DbYH
Using the typecasting operation we can call the GetData method in Main.
https://dotnetfiddle.net/laiKNC
Option1: Overriding the ToString() Method
When we put the dot operator after the ArrayList object name, we were getting the default ToString() method.
So we have another option to override the ToString() and make it return a string that we would like to get.
We are currently here, where the ToString() method call of the Student object giving us only the object type:
https://dotnetfiddle.net/acGqQj
We will write an override method for ToString in Student class.
https://dotnetfiddle.net/RZdeOj
Now without typecasting we are able to get the required output.
https://dotnetfiddle.net/gxbMGy
Exercise2: Create a C# program that uses a Hashtale to store a list of people. First prepare a class called Person.cs with two properties (name and age) and a ToString() method to print the result. Then define a Hashtale and request the information (name and age) of three people from the user. To end the program it prints the data of the people going through the list of data.
UnAnswered : What is the need for Add method in Hashtable if we are able to store new values to the Hashtable using the = operator? https://dotnetfiddle.net/TYZrVR
References:
https://www.c-sharpcorner.com/UploadFile/e83792/CSharp-HashTable/
https://www.c-sharpcorner.com/blogs/hashtable-in-c-sharp-with-example
https://www.geeksforgeeks.org/c-sharp-hashtable-with-examples/
https://www.dotnetperls.com/hashtable#:~:text=You%20can%20loop%20through%20the,DictionaryEntry%20in%20a%20foreach%2Dloop.&text=DictionaryEntry%20In%20foreach%20we%20use,the%20key%20and%20the%20value.
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable?view=net-5.0
https://www.tutorialspoint.com/csharp/csharp_hashtable.htm