How to handle Collisions when using a Custom Hash Function in a HashMap?
Last Updated :
03 Apr, 2024
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"));
}
}
OutputValue 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"));
}
}
OutputValue 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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read