How to Implement a Custom Hash function for Keys in a HashMap in Java?
Last Updated :
29 Feb, 2024
Improve
In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java.
In Java, implementing the custom hash function for keys in a HashMap requires overriding the hashcode() method in the class of the keys to correctly identify and store the keys in the HashMap. The hashcode() method generates a hash code for an object, which is used by HashMap.
Program to Implement a Custom Hash Function For Keys in a HashMap
Below is the Program to Implement a Custom Hash Function For Keys in a HashMap:
// Java Program to Implement a Custom
// Hash function for keys in a HashMap
import java.util.HashMap;
// Driver Class
public class GfGCustomHashCode
{
// Main Method
public static void main(String[] args) {
// Create a HashMap with CustomKey as keys
HashMap<CustomKey, String> map = new HashMap<>();
// Create CustomKey objects
CustomKey key1 = new CustomKey("key1");
CustomKey key2 = new CustomKey("key2");
CustomKey key3 = new CustomKey("key3");
// Put key-value pairs into the map
map.put(key1, "Java");
map.put(key2, "JavaScript");
map.put(key3, "Java");
System.out.println(map);
// retrieve values using keys
System.out.println(map.get(key1));
System.out.println(map.get(key2));
System.out.println(map.get(key3));
}
}
class CustomKey
{
private String keyData;
public CustomKey(String keyData)
{
this.keyData = keyData;
}
// Override hashCode() method
@Override
public int hashCode() {
return keyData.hashCode();
}
// Override equals() method
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
CustomKey other = (CustomKey) obj;
return keyData.equals(other.keyData);
}
// Override toString() method
@Override
public String toString() {
return keyData;
}
}
Output
{key1=Java, key2=JavaScript, key3=Java} Java JavaScript Java
Explanation of the Program:
- We have defined a
HashMap
that uses custom keys and stores string values. - Each
CustomKey
is associated with a string, and theHashMap
is populated with three key-value pairs. - Then the
CustomKey
class overrides thehashCode()
,equals()
, andtoString()
methods. - This identified that keys are correctly identified and stored in the
HashMap
. - After that, it retrieves the values associated with each key from the
HashMap
and prints them.