Java Map hashCode() Method
In Java, the hashCode() method is a part of the Object class and is used to generate a hash code value for an object.
Example 1: Hash Code for Different Objects
The below Java program demonstrates that every object has a unique hashcode.
// Java program to demonstrates hashCode()
// for different objects
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// Create two different object
Object o1 = new Object();
Object o2 = new Object();
System.out.println("HashCode of obj1: "
+ o1.hashCode());
System.out.println("HashCode of obj2: "
+ o2.hashCode());
}
}
Output
HashCode of obj1: 1510467688 HashCode of obj2: 868693306
Note: The hashCode() method generates a hash code based on the objects’s memory address or internal data.
Syntax of hashCode() Method
public int hashCode()
Return Type: This method returns an integer value that represent the hash code of the object.
Example 2: This example demonstrates storing key-value pair in a HashMap and retrieving its hash code.
// Java Program to demonstrate
// combined hash code for the entire map
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "Geek1");
hm.put(2, "Geek2");
hm.put(3, "Geek3");
System.out.println("HashMap: " + hm);
// Displaying the hashcode of the map
System.out.println("HashCode of the HashMap: "
+ hm.hashCode());
}
}
Output
HashMap: {1=Geek1, 2=Geek2, 3=Geek3} HashCode of the HashMap: 206037924
Explanation: The hash code of a HashMap is calculated based on the hash codes of its key-value pairs. This ensures that two HashMap objects with identical contents will have the same hash code.