Open In App

Java Program to Implement Hash Tables with Double Hashing

Last Updated : 10 Apr, 2023
Comments
Improve
Suggest changes
8 Likes
Like
Report

Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double hashing is a collision resolving technique in an Open Addressed Hash tables. It uses the idea of applying a second hash function (myhash2) as mentioned in the code to the key when a collision occurs.

It is the technique that is used in open addressing. In this, we will use two hash functions. The first function used, is similar to linear probing(Linear probing is a scheme in computer programming for resolving collisions in hash tables, data structures for maintaining a collection of key-value pairs and looking up the value associated with a given key), table size or the "key-mod" but if the collision occurs, then the second hash function is applied.

Note: It is used in open addressing, in which we used to hash function. The first  function is used as same in linear probing (HASH_TABLE_SIZE or key-mod) but if the collision occur then the second hash function can be applied.

There are two conditions we need to keep in mind.

  • Our second hash function never evaluates to zero.
  • It must be reachable to cells i.e. all cells must probe first.

Algorithm:

h1(key) = key% hash_table_size
h2(key) = PM-(key%PM)*PM 
// where PM is prime number

Implementation:

Example

 
 


Output
Hash Table Testing

Hash Table
prime 97
even 96
odd 95


 

Example 2


 

 
 


Output
Hash Table Testing

Hash Table
prime 97
even 96
odd 95

Hash Table
even 96
odd 95

Similarly, we can get the size of hashed table, can clear the elements from hash table, can get our desired element in hash function. In order to get 

  • For size can use ht.getSize()
  • For element can use ht.get(String)

 Where ht is object name. In the same way, we can call our other functions in the above code.


 


Next Article

Similar Reads