The Wayback Machine - https://web.archive.org/web/20240926161307/https://www.geeksforgeeks.org/implementing-our-own-hash-table-with-separate-chaining-in-java/
Open In App

Implementing our Own Hash Table with Separate Chaining in Java

Last Updated : 13 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone must be clear with the working of a hash table before moving on to the implementation aspect. So here is a brief background on the working of a hash table, and also it should be noted that we will be using Hash Map and Hash Table terminology interchangeably though in Java HashTables are thread-safe while HashMaps are not.

The code we are going to implement is available at Link 1 and Link2 

But it is strongly recommended that one must read this blog completely and try and decipher the nitty-gritty of what goes into implementing a hash map and then try to write the code yourself.

Background: Every hash-table stores its data in the form of a (key, value) combination. Interestingly every key is unique in a Hash Table but values can repeat which means values can be the same for different keys present in it. Now as we observe in an array to fetch a value we provide the position/index corresponding to the value in that array. In a Hash Table, instead of an index, we use a key to fetch the value corresponding to that key. Now the entire process is described below

Every time a key is generated. The key is passed to a hash function. Every hash function has two parts a Hash code and a Compressor. 

Hash code is an Integer number (random or non-random). In Java, every object has its own hash code. We will use the hash code generated by JVM in our hash function and compress the hash code we modulo(%) the hash code by the size of the hash table. So modulo operator is a compressor in our implementation.

The entire process ensures that for any key, we get an integer position within the size of the Hash Table to insert the corresponding value.

So the process is simple, the user gives a (key, value) pair set as input, and based on the value generated by the hash function an index is generated to where the value corresponding to the particular key is stored. So whenever we need to fetch a value corresponding to a key, that is just O(1).

This picture stops being so rosy and perfect when the concept of a hash collision is introduced. Imagine for different key values same block of the hash table is allocated now where do they previously store values corresponding to some other previous key go. We certainly can’t replace it. That will be disastrous! To resolve this issue we will use the Separate Chaining Technique, Please note there are other open addressing techniques like double hashing and linear probing whose efficiency is almost the same as that of separate chaining, and you can read more about them at Link 1 Link 2 Link3

Now what we do is make a linked list corresponding to the particular bucket of the Hash Table, to accommodate all the values corresponding to different keys that map to the same bucket. 

Now there may be a scenario where all the keys get mapped to the same bucket, and we have a linked list of n(size of the hash table) size from one single bucket, with all the other buckets empty and this is the worst case where a hash table acts a linked list and searching is O(n). 

hash collision and load factor

So what do we do?

Load Factor: If n be the total number of buckets we decided to fill initially say 10 and let’s say 7 of them got filled now, so the load factor is 7/10=0.7. 

In our implementation whenever we add a key-value pair to the Hash Table we check the load factor if it is greater than 0.7 we double the size of our hash table.

Implementation of a Hash Table in Java

Hash Node Data Type 

We will try to make a generic map without putting any restrictions on the data type of the key and the value. Also, every hash node needs to know the next node it is pointing to in the linked list so a next pointer is also required.

The functions we plan to keep in our hash map are  as follows: 

  • get(K key): returns the value corresponding to the key if the key is present in HT (Hast Table)
  • getSize() : return the size of the HT
  • add(): adds a new valid key, value pair to the HT, if already present updates the value
  • remove() : removes the key, value pair
  • isEmpty() : returns true if size is zero
ArrayList<HashNode<K, V>> bucket = new ArrayList<>();

A Helper Function is implemented to get the index of the key, to avoid redundancy in other functions like get, add and remove. This function uses the inbuilt java function to generate a hash code, and we compress the hash code by the size of the HT so that the index is within the range of the size of the HT

get(): 

The get function just takes a key as an input and returns the corresponding value if the key is present in the table otherwise returns null. Steps are:  

  • Retrieve the input key to find the index in the HT
  • Traverse the linked list corresponding to the HT if you find the value then return it else if you fully traverse the list without returning it means the value is not present in the table and can’t be fetched so return null

remove(): 

  • Fetch the index corresponding to the input key using the helper function
  • The traversal of the linked list is similar to in get() but what is special here is that one needs to remove the key along with finding it and two cases arise
  • If the key to be removed is present at the head of the linked list
  • If the key to be removed is not present at the head but somewhere else

add():

Now to the most interesting and challenging function of this entire implementation. It is interesting because we need to dynamically increase the size of our list when the load factor is above the value we specified.  

  • Just like removing steps till traversal and adding and two cases (addition at head spot or non-head spot) remain the same.
  • Towards the end, if the load factor is greater than 0.7
  • We double the size of the array list and then recursively call add function on existing keys because in our case hash value generated uses the size of the array to compress the inbuilt JVM hash code we use, so we need to fetch the new indices for the existing keys. This is very important to understand please re-read this paragraph till you get a hang of what is happening in the add function.

Java does in its own implementation of Hash Table uses Binary Search Tree if linked list corresponding to a particular bucket tends to get too long. 

Java
// Java program to demonstrate implementation of our
// own hash table with chaining for collision detection
import java.util.ArrayList;
import java.util.Objects;

// A node of chains
class HashNode<K, V> {
    K key;
    V value;
      final int hashCode;

    // Reference to next node
    HashNode<K, V> next;

    // Constructor
    public HashNode(K key, V value, int hashCode)
    {
        this.key = key;
        this.value = value;
          this.hashCode = hashCode;
    }
}

// Class to represent entire hash table
class Map<K, V> {
    // bucketArray is used to store array of chains
    private ArrayList<HashNode<K, V> > bucketArray;

    // Current capacity of array list
    private int numBuckets;

    // Current size of array list
    private int size;

    // Constructor (Initializes capacity, size and
    // empty chains.
    public Map()
    {
        bucketArray = new ArrayList<>();
        numBuckets = 10;
        size = 0;

        // Create empty chains
        for (int i = 0; i < numBuckets; i++)
            bucketArray.add(null);
    }

    public int size() { return size; }
    public boolean isEmpty() { return size() == 0; }
    
      private final int hashCode (K key) {
        return Objects.hashCode(key);
    }
  
    // This implements hash function to find index
    // for a key
    private int getBucketIndex(K key)
    {
        int hashCode = hashCode(key);
        int index = hashCode % numBuckets;
        // key.hashCode() could be negative.
        index = index < 0 ? index * -1 : index;
        return index;
    }

    // Method to remove a given key
    public V remove(K key)
    {
        // Apply hash function to find index for given key
        int bucketIndex = getBucketIndex(key);
        int hashCode = hashCode(key);
        // Get head of chain
        HashNode<K, V> head = bucketArray.get(bucketIndex);

        // Search for key in its chain
        HashNode<K, V> prev = null;
        while (head != null) {
            // If Key found
            if (head.key.equals(key) && hashCode == head.hashCode)
                break;

            // Else keep moving in chain
            prev = head;
            head = head.next;
        }

        // If key was not there
        if (head == null)
            return null;

        // Reduce size
        size--;

        // Remove key
        if (prev != null)
            prev.next = head.next;
        else
            bucketArray.set(bucketIndex, head.next);

        return head.value;
    }

    // Returns value for a key
    public V get(K key)
    {
        // Find head of chain for given key
        int bucketIndex = getBucketIndex(key);
          int hashCode = hashCode(key);
      
        HashNode<K, V> head = bucketArray.get(bucketIndex);

        // Search key in chain
        while (head != null) {
            if (head.key.equals(key) && head.hashCode == hashCode)
                return head.value;
            head = head.next;
        }

        // If key not found
        return null;
    }

    // Adds a key value pair to hash
    public void add(K key, V value)
    {
        // Find head of chain for given key
        int bucketIndex = getBucketIndex(key);
          int hashCode = hashCode(key);
        HashNode<K, V> head = bucketArray.get(bucketIndex);

        // Check if key is already present
        while (head != null) {
            if (head.key.equals(key) && head.hashCode == hashCode) {
                head.value = value;
                return;
            }
            head = head.next;
        }

        // Insert key in chain
        size++;
        head = bucketArray.get(bucketIndex);
        HashNode<K, V> newNode
            = new HashNode<K, V>(key, value, hashCode);
        newNode.next = head;
        bucketArray.set(bucketIndex, newNode);

        // If load factor goes beyond threshold, then
        // double hash table size
        if ((1.0 * size) / numBuckets >= 0.7) {
            ArrayList<HashNode<K, V> > temp = bucketArray;
            bucketArray = new ArrayList<>();
            numBuckets = 2 * numBuckets;
            size = 0;
            for (int i = 0; i < numBuckets; i++)
                bucketArray.add(null);

            for (HashNode<K, V> headNode : temp) {
                while (headNode != null) {
                    add(headNode.key, headNode.value);
                    headNode = headNode.next;
                }
            }
        }
    }

    // Driver method to test Map class
    public static void main(String[] args)
    {
        Map<String, Integer> map = new Map<>();
        map.add("this", 1);
        map.add("coder", 2);
        map.add("this", 4);
        map.add("hi", 5);
        System.out.println(map.size());
        System.out.println(map.remove("this"));
        System.out.println(map.remove("this"));
        System.out.println(map.size());
        System.out.println(map.isEmpty());
    }
}

Output
3
4
null
2
false

Time and Space Complexities

Add Method:

  • Time Complexity: O(1)
  • Space Complexity: O(n)

This method adds a key value pair to the hash table. The time complexity of this method is O(1) because it is constant time. The space complexity is O(n) because it will increase with the amount of items stored in the hash table.

Remove Method:

  • Time Complexity: O(1)
  • Space Complexity: O(1)

This method removes a given key from the hash table. The time complexity of this method is O(1) because it is constant time. The space complexity is O(1) because it does not depend on the amount of items stored in the hash table.

Get Method:

  • Time Complexity: O(1)
  • Space Complexity: O(1)

This method returns the value for a given key from the hash table. The time complexity of this method is O(1) because it is constant time. The space complexity is O(1) because it does not depend on the amount of items stored in the hash table.

Size Method:

  • Time Complexity: O(1)
  • Space Complexity: O(1)

The time complexity is constant because it simply returns the size of the hash table. The space complexity is constant because it does not require any additional space.




Previous Article
Next Article

Similar Reads

Implementation of Hash Table in Python using Separate Chaining
A hash table is a data structure that allows for quick insertion, deletion, and retrieval of data. It works by using a hash function to map a key to an index in an array. In this article, we will implement a hash table in Python using separate chaining to handle collisions. Separate chaining is a technique used to handle collisions in a hash table.
7 min read
Implementation of Hash Table in C/C++ using Separate Chaining
Introduction: Hashing is a technique that maps a large set of data to a small set of data. It uses a hash function for doing this mapping. It is an irreversible process and we cannot find the original value of the key from its hashed value because we are trying to map a large set of data into a small set of data, which may cause collisions. It is n
10 min read
Implementing own Hash Table with Open Addressing Linear Probing
Prerequisite - Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in JavaIn Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed). Insert(k) - Keep probing u
13 min read
How to implement our own Dynamic Array class in Java?
Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. ArrayList elements are placed in contiguous storage so that
4 min read
Separate Chaining Collision Handling Technique in Hashing
Separate Chaining is a collision handling technique. Separate chaining is one of the most popular and commonly used techniques in order to handle collisions. In this article, we will discuss about what is Separate Chain collision handling technique, its advantages, disadvantages, etc. What is Collision? Since a hash function gets us a small number
4 min read
Compile our own Android Kernel in 5 Simple Steps
The Android kernel helps the applications to communicate with the hardware components of the device. For example: Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies. Another example is power saver mode. It instructs the processor and the graphics proce
3 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can b
5 min read
What are Hash Functions and How to choose a good Hash Function?
Prerequisite: Hashing | Set 1 (Introduction) What is a Hash Function? A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. W
5 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Method Chaining In Java with Examples
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.). Method chaining in Java is a common syntax to invoke multiple methods c
3 min read
Constructor Chaining In Java with Examples
Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. Prerequisite - Constructors in Java Constructor chaining
5 min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Various load balancing techniques used in Hash table to ensure efficient access time
Load balancing refers to the process of distributing workloads evenly across multiple servers, nodes, or other resources to ensure optimal resource utilization, maximize output, minimize response time, and avoid overload of any single resource. Load balancing helps to improve the reliability and scalability of applications and systems, as well as r
3 min read
Hash Table vs Trie
What is Hash Table? An array that stores pointers to records corresponding to a given element. An entry in the hash table is NIL if no existing element has a hash function value equal to the index for the entry. In simple terms, we can say that a hash table is a generalization of the array. Hash table gives the functionality in which a collection o
5 min read
Hash Table vs STL Map
This article focus on : Compare and contrast Hash table and an STL Map. How is the hash table implemented? If the number of inputs is small, which data structure options can be used instead of a hash table? Hash table In a hash table, a value is stored by calling a hash function on a key. Values are not stored in sorted order.Additionally, since ha
4 min read
Why use an Array to implement a "list" instead of a Hash Table?
What is an Array?An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. C/C++ Code #include <iostream> using namespace std; // driver program int main() { // initaizling array int arr[] = {1, 2,
4 min read
Advantages of BST over Hash Table
Hash Table supports following operations in O(1) time. 1) Search 2) Insert 3) Delete The time complexity of above operations in a self-balancing Binary Search Tree (BST) (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(Logn). So Hash Table seems to beating BST in all common operations. When should we prefer BST over Hash Tables, what are advan
2 min read
Hash Table Data Structure
What is Hash Table?A Hash table is defined as a data structure used to insert, look up, and remove key-value pairs quickly. It operates on the hashing concept, where each key is translated by a hash function into a distinct index in an array. The index functions as a storage location for the matching value. In simple words, it maps the keys with th
11 min read
Dividing a Large file into Separate Modules in C/C++, Java and Python
If you ever wanted to write a large program or software, the most common rookie mistake is to jump in directly and try to write all the necessary code into a single program and later try to debug or extend later. This kind of approach is doomed to fail and would usually require re-writing from scratch. So in order to tackle this scenario, we can tr
14 min read
Hashtables Chaining with Doubly Linked Lists
Prerequisite - Hashing Introduction, Hashtable using Singly Linked List & Implementing our Own Hash Table with Separate Chaining in Java Implementing hash table using Chaining through Doubly Linked List is similar to implementing Hashtable using Singly Linked List. The only difference is that every node of Linked List has the address of both, t
12 min read
Java | How to create your own Helper Class?
Helper Class is a Java class which includes basic error handling, some helper functions etc. Helper class contains functions that help in assisting the program. This Class intends to give quick implementation of basic functions such that programmers do not have to implement again and again. It is easy to Access as all the member functions are stati
5 min read
How to Create Your Own Annotations in Java?
Annotations are a form of metadata that provide information about the program but are not a part of the program itself. An Annotation does not affect the operation of the code they Annotate. Now let us go through different types of java annotations present that are listed as follows: Predefined annotations.: @Deprecated, @Override, @SuppressWarning
5 min read
Learn Java on Your Own in 20 Days - Free!
Indeed, JAVA is one of the most demanding programming languages in the IT world. Statistically, there are around 7-8 million JAVA Developers across the world and the number is growing rapidly. Needless to say, JAVA has a lot of career opportunities in the tech market and the language will undoubtedly remain in demand in the upcoming times as well.
7 min read
Segregate 1s and 0s in separate halves of a Binary String
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required. Examples: Input: str = "01011100"Output: 2Explanation: The operations performed are as follows: "01011100" -> "11101000"
5 min read
Sort and separate odd and even numbers in an Array using custom comparator
Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = { 5, 3, 2, 8, 7, 4, 6, 9, 1 }Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = { 12, 15, 6, 2, 7, 13, 9, 4 }Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa
5 min read
Minimize cost to reach bottom right from top left corner of Matrix with given separate cost for each move
Given an integer N and three N x N matrices X[][], Y[][], and Z[][], the task is to calculate the minimum cost required to reach the bottom right from the top left of the matrix using the following moves: Move to a cell in the right direction from (i, j) which will cost X[i][j].Move to a cell in the downward direction from (i, j) which will cost Y[
15+ min read
SHA-256 Hash in Java
Definition: In Cryptography, SHA is cryptographic hash function which takes input as 20 Bytes and rendered the hash value in hexadecimal number, 40 digits long approx.Message Digest Class: To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographi
2 min read
Java | Implementing Iterator and Iterable Interface
Iterators are used in Collection framework in Java to retrieve elements one by one. For more details and introduction related to this, see this link. Why it is needed to implement Iterable interface? Every class that implements Iterable interface appropriately, can be used in the enhanced For loop (for-each loop). The need to implement the Iterator
4 min read
Implementing next_permutation() in Java with Examples
Given an array or string, the task is to find the next lexicographically greater permutation of it in Java.Examples: Input: string = "gfg" Output: ggf Input: arr[] = {1, 2, 3} Output: {1, 3, 2} In C++, there is a specific function that saves us from a lot of code. It’s in the header file #include<algorithm>. The function is next_permutation(a
5 min read
Implementing Self Organizing List in Java
A Self-Organizing List is a list that modifies the order in which elements are stored based on the actual or expected access pattern. The goal is to achieve an ordering that keeps the most frequently sought elements closest to improve average access time. This property is also known as the locality of reference that brings the most frequently used
4 min read
Article Tags :
Practice Tags :