Java AbstractMap hashCode() Method
The hashCode() method of the AbstractMap class in Java is used to calculate a hash code value for a map. This hash code is based on the key-value mapping contained in the map. It ensures consistency such that two maps with the same entries have the same hash code.
Example 1: Hash Code of a Non-Empty Map
// Java program demonstrate the working of hashCode()
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
// Create a HashMap
Map<String, Integer> hm = new HashMap<>();
// Add key-value pairs
hm.put("Java", 1);
hm.put("Programnming", 2);
hm.put("Language", 3);
// Get hashCode
System.out.println("Map: " + hm);
System.out.println("HashCode: " + hm.hashCode());
}
}
Output
Map: {Programnming=2, Java=1, Language=3} HashCode: -95421541
Explanation: In the above example, it creates a HashMap and adds three key-value pairs to it. The hashCode() method calculates a unique integer value based on the keys and values in the map.
Syntax of AbstractMap hashCode() Method
public int hashCode()
Return Type: It returns an integer representing the hash code value of the map.
Example 2: Hash Code of an Empty Map
// Java programm to demonstrates the
// hash code of an empty HashMap
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
// creating an empty HashMap
Map<String, Integer> hm1 = new HashMap<>();
System.out.println("Empty Map: " + hm1);
System.out.println("HashCode of Empty Map: "
+ hm1.hashCode());
}
}
Output
Empty Map: {} HashCode of Empty Map: 0
Explanation: The above program creates an empty HashMap without any key-value pairs. The hashCode() method returns 0 because no entries exist in the map.