The equals() method of java.util.HashSet class is used verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order.
Syntax:
public boolean equals(Object o)
Parameters: This method takes the object o as a parameter to be compared for equality with this set.
Returns Value: This method returns true if the specified object is equal to this set.
Below are the examples to illustrate the equals() method.
Example 1:
| // Java program to demonstrate equals()// method of HashSet Âimportjava.util.*; ÂpublicclassGFG {    publicstaticvoidmain(String[] argv)    { Â        // Creating object of HashSet<String>        HashSet<String>            arrset1 = newHashSet<String>(); Â        // Populating arrset1        arrset1.add("A");        arrset1.add("B");        arrset1.add("C");        arrset1.add("D");        arrset1.add("E"); Â        // print arrset1        System.out.println("First HashSet: "                           + arrset1); Â        // Creating another object of HashSet<String>        HashSet<String>            arrset2 = newHashSet<String>(); Â        // Populating arrset2        arrset2.add("A");        arrset2.add("B");        arrset2.add("C");        arrset2.add("D");        arrset2.add("E"); Â        // print arrset2        System.out.println("Second HashSet: "                           + arrset2); Â        // comparing first HashSet to another        // using equals() method        booleanvalue            = arrset1.equals(arrset2); Â        // print the value        System.out.println("Are both set equal: "                           + value);    }} | 
First HashSet: [A, B, C, D, E] Second HashSet: [A, B, C, D, E] Are both set equal: true
Example 2:
| // Java program to demonstrate equals()// method of HashSet Âimportjava.util.*; ÂpublicclassGFG1 {    publicstaticvoidmain(String[] argv)    { Â        // Creating object of HashSet        HashSet<Integer>            arrset1 = newHashSet<Integer>(); Â        // Populating arrset1        arrset1.add(10);        arrset1.add(20);        arrset1.add(30);        arrset1.add(40);        arrset1.add(50); Â        // print arrset1        System.out.println("First HashSet: "                           + arrset1); Â        // Creating another object of HashSet        HashSet<Integer>            arrset2 = newHashSet<Integer>(); Â        // Populating arrset2        arrset2.add(10);        arrset2.add(20);        arrset2.add(30); Â        // print arrset2        System.out.println("Second HashSet: "                           + arrset2); Â        // comparing first HashSet to another        // using equals() method        booleanvalue = arrset1.equals(arrset2); Â        // print the value        System.out.println("Are both set equal: "                           + value);    }} | 
First HashSet: [50, 20, 40, 10, 30] Second HashSet: [20, 10, 30] Are both set equal: false


 
                                    







