Java Hashtable equals(Object o) Example

The equals(Object o) method of java.util.Hashtable class compares the specified Object with this Map for equality and returns true if the specified Object is equal to this Map

Signature

public boolean equals(Object o)

This method compares the specified Object with this Map for equality and returns true if the specified Object is equal to this Map

Example

The following example shows the usage of java.util.Hashtable.equals(o) method.

import java.util.Hashtable;
import java.util.Map;

public class EqualsMethodHashtableExample 
{
    public static void main(String args[])
    {
        // create an empty Hashtable
        Hashtable<Integer,String>  hashtable1 = new Hashtable<Integer,String>();
        
        // use put() method to put elements to the Hashtable
        hashtable1.put(1,"Element1");
        hashtable1.put(2,"Element2");
        hashtable1.put(3,"Element3");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        
        //create a new Hashtable hashtable2
        Hashtable<Integer,String>  hashtable2 = new Hashtable<Integer,String>();
        
        //put elements to the Hashtable2
        hashtable2.put(1,"Element1");
        hashtable2.put(2,"Element2");
        hashtable2.put(3,"Element3");
        hashtable2.put(4,"Element4");
        hashtable2.put(5,"Element5");
        
        //Check the equality of hashtable1 and hashtable2
        System.out.println("Is \"hashtable1\" equal to \"hashtable2\" : "+hashtable1.equals(hashtable2));
        
        //Lets remove the element from hashtable2
        hashtable2.remove(2);
        
        //Printing the elements of the hashtable2
        for(Map.Entry<Integer,String> entry : hashtable2.entrySet() )
        {
            System.out.println("Key : "+entry.getKey()+" value : "+entry.getValue());
        }
        
      //Lets again Check the equality of hashtable1 and hashtable2
        System.out.println("Is \"hashtable1\" equal to \"hashtable2\" : "+hashtable1.equals(hashtable2));
    }
}

Output

Is "hashtable1" equal to "hashtable2" : true
Key : 5 value : Element5
Key : 4 value : Element4
Key : 3 value : Element3
Key : 1 value : Element1
Is "hashtable1" equal to "hashtable2" : false

Leave a Reply

Your email address will not be published. Required fields are marked *