Home > Backend Development > C++ > body text

How to store/update hash table elements?

PHPz
Release: 2023-08-29 17:21:08
forward
1414 people have browsed it

How to store/update hash table elements?

A hash table is a data structure composed of a collection of key-value pairs. A hash table collection uses a hash function to calculate the hash code of a key. A hash table can also be defined as a non-universal collection of key-value pairs.

The hash code for each key is calculated using a hash function and stored in different buckets internally. When accessing a value, matches this hash code with the hash code of the specified key and returns the result.

Unlike other data structures such as stacks, queues, and ArrayLists that store single values, hash table collections store double values ​​in the form of key-value pairs. Each key-value pair forms an element of the hash table.

Let us discuss in this article how to store and update elements in a hash table collection.

How to store/update items in Hashtable?

We can store or add elements in the hash table, and we can also update existing elements in the hash table. These are two different operations we can perform on a collection of hash tables.

To add elements to the hash table collection, we use the "Add" method of the Hashtable class provided in C#.

To update the elements of the hash table, we use the assignment operator to replace the value.

Add elements to hash table

We can add elements to the hash table in two ways.

  • Use initializer for hash table

  • Use Add method

In the first method of using an initializer, we initialize the hash table object using key-value pairs when declaring the hash table object.

This will create a hash table object with initial key-value pairs. Let us walk through a programming example to demonstrate how to add elements to a hash table using initialization.

Example

using System;
using System.Collections;
class MyHashTable {
   public static void Main() {
      
      // Create a Hashtable
      Hashtable prog_lang = new Hashtable(){{"001", "C#"},
         {"002", "C++"},
         {"003", "Java"},
         {"004", "Python"},
         {"005", "Perl"}
      };
      
      //print original hashtable
      Console.WriteLine("Hashtable items:");
      foreach(DictionaryEntry entry in prog_lang){
         Console.WriteLine("{0} => {1} ", entry.Key, entry.Value);
      }
   }
}
Copy after login

In this example, first, we use the "new" keyword to create an object of type Hashtable named "prog_lang" and initialize it to five key-value pairs of numbers (keys) and the name of the programming language ( value). < /p>

We then print the contents of that hash table by looping over the hash table using "foreach".

Output

The program generates the following.

Hashtable items:
005 => Perl 
004 => Python 
002 => C++ 
003 => Java 
001 => C# 
Copy after login
Copy after login

This program only displays the contents of the hash table.

The add method is provided by the Hashtable class and can be used to add elements to the Hashtable object. Add methods have the following general syntax.

HashTable.add("key", "value")

Example

The following program demonstrates the Add method of storing elements in a hash table collection.

using System;
using System.Collections;
class MyHashTable {
   public static void Main() {
        
      // Create a Hashtable
      Hashtable prog_lang = new Hashtable();
      prog_lang.Add("001", "C#");
      prog_lang.Add("002", "C++");
      prog_lang.Add("003", "Java");
      prog_lang.Add("004", "Python");
      prog_lang.Add("005", "Perl");
      
      //print original hashtable
      Console.WriteLine("Hashtable items:");
      foreach(DictionaryEntry entry in prog_lang){
         Console.WriteLine("{0} => {1} ", entry.Key, entry.Value);
      }
   }
}
Copy after login

This program is similar to the previous one, except here we use the Add method to add elements to the hash table. So here we add the same five elements consisting of numbers (keys) and programming language names (values) to a hash table and then display the contents of the hash table.

Output

The output of the program is shown below.

Hashtable items:
005 => Perl 
004 => Python 
002 => C++ 
003 => Java 
001 => C# 
Copy after login
Copy after login

As shown in the figure, the contents of the hash table are displayed in the output.

Update elements in the hash table

Elements in a hash table can be updated by passing the key in the indexer. This way we can retrieve the value and update the value.

For example, given the hash table cities. If one of the keys is IN and we want to update the value of this key, we can write:

Cities["IN"] = "Mumbai";

This will update the existing value of the key.

But please note that since Hashtable is a non-generic collection, we must type the case of the value if we want to retrieve it.

Example

Let us consider the following example where we update an element of a hash table.

using System;
using System.Collections;
class MyHashTable {
   public static void Main() {
      
      // Create a Hashtable
      Hashtable cities = new Hashtable();
      
      // Add elements to the Hashtable
      cities.Add("UK", "London, Liverpool, Bristol");
      cities.Add("USA", "Los Angeles, Boston, Washington");
      cities.Add("India", "New Delhi, Mumbai, Kolkata");
      
      //print original hashtabel
      Console.WriteLine("Hashtable items:");
      foreach(DictionaryEntry entry in cities){
         Console.WriteLine("{0} => {1} ", entry.Key, entry.Value);
      }
      
      //update hashtable with new values for US and UK
      cities["UK"] = "Manchester, Birmingham, Leeds";
      cities["USA"] = "Chicago, New York, Texas";
      
      //print updated hashtable
      Console.WriteLine("Hashtable items after Updation:");
      foreach(DictionaryEntry entry in cities){
         Console.WriteLine("{0} ==> {1} ", entry.Key, entry.Value);
      }
   }
}
Copy after login

In this program we have a "city" hash table. Each key (city code) is mapped to multiple values. First, we display the original contents of the hash table. Then we update the values ​​of two keys (USA and UK). again We display the updated hash table.

Output

This program displays the following output.

Hashtable items:
USA => Los Angeles, Boston, Washington 
India => New Delhi, Mumbai, Kolkata 
UK => London, Liverpool, Bristol 

Hashtable items after Updation:
USA ==> Chicago, New York, Texas 
India ==> New Delhi, Mumbai, Kolkata 
UK ==> Manchester, Birmingham, Leeds 
Copy after login

Please note that we did not update the value of Key = India. The remaining key values ​​are updated and they appear in the second group of output.

Example

Let's consider another example. Here we use an initializer to initialize the hash table object instead of adding values ​​using the Add method.

using System;
using System.Collections;
class MyHashTable {
   public static void Main() {
      // Create a Hashtable
      Hashtable phonetics = new Hashtable() {
         {"A", "Apple"},
         {"B", "Bat"},
         {"C", "Cat"}
      };
      
      //print original hashtabel
      Console.WriteLine("Hashtable items:");
      foreach(DictionaryEntry entry in phonetics) {
         Console.WriteLine("{0} => {1} ", entry.Key, entry.Value);
      }
      
      //update hashtable with new values for all keys
      phonetics["A"] = "Ant, Anchor, Arm";
      phonetics["B"] = "Ball, Baby, Beam";
      phonetics["C"] = "Car, Cake, Camel";
      
      //print updated hashtable
         Console.WriteLine("Hashtable items after Updation:");
      foreach(DictionaryEntry entry in phonetics) {
         Console.WriteLine("{0} ==> {1} ", entry.Key, entry.Value);
      }
   }
}
Copy after login

Here, we use a phonetic symbol hash table. First, we initialize the hash table object and set a value for each key. Then we updated multiple values ​​for each key.

Output

The program generates the following output.

Hashtable items:
A => Apple 
B => Bat 
C => Cat 

Hashtable items after Updation:
A ==> Ant, Anchor, Arm 
B ==> Ball, Baby, Beam 
C ==> Car, Cake, Camel 
Copy after login

We can see the different output before and after the update.

In this article, we discussed methods of storing and updating values ​​in hash tables. We can store values ​​by initializing a hash table object using new operator during declaration. We can also store objects in a hash table using the Add method. To update a value in a hash table, we can access the key of an element and then use the assignment operator to update its value.

The above is the detailed content of How to store/update hash table elements?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template