Open In App

Java AbstractMap equals() Method

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The equals() method of the Java AbstractMap class is used to check equality between two maps. It compares the key-value pair in the current map with the key-value pair of the specified map.

Syntax of AbstarctMap equals() Method

public boolean equals(Object o)

  • Parameter: The Object to be compared with the current map.
  • Return Type: Return “true” if the specified object is equal to the current map, otherwise return “false”.

Example: This example demonstrates how the equals() method checks for equality between different HashMap instances based on their key-value mapping.

Java
// Java code to demonstrate the working of equals()
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class Geeks {
    public static void main(String[] args)
    {    
        // Creating three HashMap instances
        Map<String, Integer> hm1 = new HashMap<>();
        hm1.put("Geek1", 1);
        hm1.put("Geek2", 2);
        hm1.put("Geek3", 3);

        Map<String, Integer> hm2 = new HashMap<>();
        hm2.put("Geek3", 3);
        hm2.put("Geek2", 2);
        hm2.put("Geek1", 1);

        Map<String, Integer> hm3 = new HashMap<>();
        hm3.put("Geek1", 1);
        hm3.put("Geek2", 2);
        hm3.put("Geek4", 4);

        System.out.println("First HashMap: " + hm1);
        System.out.println("Second HashMap: " + hm2);
        System.out.println("Third HashMap: " + hm3);
      
        // Checking equality between the maps
        System.out.println("Is hm1 equal to hm2? " + hm1.equals(hm2));
        System.out.println("Is hm1 equal to hm3? " + hm1.equals(hm3)); 

    }
}

Output
First HashMap: {Geek3=3, Geek2=2, Geek1=1}
Second HashMap: {Geek3=3, Geek2=2, Geek1=1}
Third HashMap: {Geek4=4, Geek2=2, Geek1=1}
Is hm1 equal to hm2? true
Is hm1 equal to hm3? false

Next Article

Similar Reads