Open In App

How to handle Collisions when using a Custom Hash Function in a HashMap?

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A HashMap is a data structure that stores key-value pairs. So, the values ​​can be efficiently retrieved based on their associated keys. Hash functions are used to map keys to indices in an array. The Collisions occur when two or more different keys hash into the same index, resulting in potential data loss if not maintained properly. Handling collision is an important part of HashMap by default hash functions are used.

In this article, we will learn how to handle Collisions when using a Custom Hash Function in a HashMap.

Java Program to Handle Collisions using a Custom Hash Function in a HashMap

Due to the finite size of the array, collisions can occur when two different keys generate the same hash code. To handle collisions using a custom hash function, HashMap implementations generally use the following strategies:

Approach 1: Separate Chaining

In this approach, each index in the array holds a linked list of key-value pairs. When any collision occurs, the key-value pair is added to the linked list at that index number. To retrieve a value, traverse the linked list until we find the desired key.

Below is the Java implementation of the separate chaining approach:

Java
// Java program to handle collisions using a custom hash function using separate chaining
import java.util.LinkedList;

class MyHashMap<K, V> {
    private LinkedList<Entry<K, V> >[] buckets;
    private int capacity;

    public MyHashMap(int capacity)
    {
        this.capacity = capacity;
        buckets = new LinkedList[capacity];
        for (int i = 0; i < capacity; i++) {
            buckets[i] = new LinkedList<>();
        }
    }
    
      // Function to put value for key
    public void put(K key, V value)
    {
        int index = key.hashCode() % capacity;
        LinkedList<Entry<K, V> > bucket = buckets[index];
        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                entry.value = value;
                return;
            }
        }
        bucket.add(new Entry<>(key, value));
    }
    
      // Function to get value for key
    public V get(K key)
    {
        int index = key.hashCode() % capacity;
        LinkedList<Entry<K, V> > bucket = buckets[index];
        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                return entry.value;
            }
        }
        return null;
    }

    private static class Entry<K, V> {
        private K key;
        private V value;

        public Entry(K key, V value)
        {
            this.key = key;
            this.value = value;
        }
    }
}

public class GFG {
    public static void main(String[] args)
    {
        MyHashMap<String, Integer> map = new MyHashMap<>(5);
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("d", 4);
        map.put("e", 5);
        map.put("f", 6); // Collision occurs with "a"

        System.out.println("Value for key 'a': "
                           + map.get("a"));
        System.out.println("Value for key 'f': "
                           + map.get("f"));
    }
}

Output
Value for key 'a': 1
Value for key 'f': 6

Explanation of the above Program:

  • This Java program implements a custom HashMap that handles collisions using a technique called separate chaining.
  • It utilizes LinkedLists to store key-value pairs in buckets indexed by the hash code of keys.
  • The put() method inserts key-value pairs into the appropriate bucket, while the get() method retrieves values based on keys by searching within the corresponding bucket.
  • This approach ensures efficient storage and retrieval of data even when collisions occur, providing a robust solution for handling collisions in HashMaps.

Approach 2: Open Addressing

In this approach, when a collision occurs, the algorithm searches for an alternative location within the array to place the key-value pair. Some common techniques include linear probing, quadratic probing, and double hashing.

  • Linear Probing: In linear probing, after a collision, search adjacent buckets until an empty spot or the desired element is found. If the next bucket is occupied, move to the next one and repeat. Linear probing can lead to clustering.
  • Quadratic Probing: Quadratic Probing is similar to linear probing but uses quadratic increments (1, 3, 6, 10, 15, …) away from the collision point. Quadratic probing helps reduce clustering.
  • Double Hashing: In double hashing, we use a second hash function to determine the step size for probing. Calculate the next bucket as hash(key) + i * hash2(key). Double hashing provides better distribution than linear or quadratic probing.

Below is the Java implementation of the open addressing approach:

Java
// Java program to handle collisions using open addressing approach 
import java.io.*;
class MyHashMap<K, V> {
    private Object[] keys;
    private Object[] values;
    private int capacity;

    public MyHashMap(int capacity)
    {
        this.capacity = capacity;
        keys = new Object[capacity];
        values = new Object[capacity];
    }

    // Function to put value for key
    public void put(K key, V value)
    {
        int index = Math.abs(key.hashCode())
                    % capacity; // Ensure non-negative index
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                values[index] = value;
                return;
            }
            index
                = (index + 1) % capacity; // Linear probing
        }
        keys[index] = key;
        values[index] = value;
    }

    // Function to get value for key
    public V get(K key)
    {
        int index = Math.abs(key.hashCode())
                    % capacity; // Ensure non-negative index
        while (keys[index] != null) {
            if (keys[index].equals(key)) {
                return (V)values[index];
            }
            index
                = (index + 1) % capacity; // Linear probing
        }
        return null;
    }
}

public class GFG {
    public static void main(String[] args)
    {
        MyHashMap<String, Integer> map = new MyHashMap<>(6);
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("d", 4);
        map.put("e", 5);
        map.put("g", 7); // Collision occurs with "a"

        System.out.println("Value for key 'a': "
                           + map.get("a")); 
        System.out.println("Value for key 'g': "
                           + map.get("g")); 
    }
}

Output
Value for key 'a': 1
Value for key 'g': 7

Explanation of the above Program:

  • The provided code is an implementation of a custom HashMap using open addressing to handle collisions.
  • It stores keys and values in separate arrays and utilizes linear probing to resolve collisions.
  • The put() method inserts key-value pairs, while the get() method retrieves values based on keys, both employing hash codes to determine indices and handling collisions through linear probing.
  • This approach ensures efficient storage and retrieval of data in the HashMap.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads