Home » Hashing Techniques in Java

Hashing Techniques in Java

by Online Tutorials Library

Hashing Techniques in Java

The hash function is a key-value mapping function. When two or more keys are mapped to the same value using these hashing methods, there exists duplicate values. The use of chain hashing prevents collisions. Each hash table cell should lead to a linked list of entries that have the same hash function value.

Let’s create a hash function that returns a hash table with ‘N’ buckets.

To add a node to the hash table, we need to find the hash index for the specified key.

The hash function might also be used to figure it out.

Insert: Go to the bucket that corresponds to the hash index determined above and add the new node to the end of the list.

Delete: To remove a node from a hash table, compute the key’s hash index, move to the bucket that corresponds to the calculated hash index, search the list in the current bucket for the node with the supplied key, and remove it (if found).

Methods for Implementing hashing in Java

1. HashTable-based Method(A synchronised implementation of hashing)

HashTableDemo.java

Output:

{5=Hello, 3=You are visiting, 2=Tutoraspire, 1=website}  

Here, the above Java code demonstrates the use of Hashtable.

2. HashMap-based Method (A non-synchronized faster implementation of hashing)

HashMapDemo.java

Output:

{1=1, 5=1, 6=3, 10=2}  

The above Java code displays the use of Hashmap. It is a non-synchronized faster method for hashing.

3. LinkedHashMap-based method(Similar to HashMap, but keeps order of elements)

LinkedHashMapDemo.java

Output:

{One=Robin, Two=Satyam, Three=Kanishk}  Getting value for key 'one': Robin  Size of the Hashmap: 3  Is Hashmap empty? false  Contains key 'two'? true  Contains value 'Kanishk? true  delete element 'one': Robin  {Two=Satyam, Three=Kanishk}  

In the above program LinkedHashMap is used with its different methods such as size(), get(), isEmpty(), containsKey(), containsValue(), remove().

4. ConcurretHashMap-based Method (Similar to HashTable, Synchronized, but faster as multiple locks are used)

DemoforConcurrentHashMap.java

Output:

ConcurentHashMap: {201=How, 202=are, 203=you}  ConcurentHashMap: {201=How, 202=are, 203=you}  ConcurentHashMap: {201=Who, 202=are, 203=you}  ConcurentHashMap: {201=Who, 202=are}  

The above Java program displays an implementation of ConcurrentHashMap with its different methods such as put(), putIfAbsent(), replace(), remove().


You may also like