The AbstractSet equals() Method in Java is used to check for equality between two sets. This method verifies whether the elements of one set are equal to the elements of another set.
Syntax of AbstractSet equals() Method
public boolean equals(Object o)
- Parameter: The object "o" is to be compared for equality with this set.
- Return Type: This method returns "true" if both sets contain the same elements, otherwise returns "false".
Example: This example checks if two sets are equal by verifying that they contain the same elements, regardless of their order.
// Java program to demonstrates the working of equals()
import java.util.HashSet;
import java.util.Set;
public class Geeks {
public static void main(String[] args)
{
// Create three sets
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(2);
s1.add(3);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(2);
s2.add(1);
Set<Integer> s3 = new HashSet<>();
s3.add(1);
s3.add(2);
s3.add(4);
System.out.println("Set1: " + s1);
System.out.println("Set2: " + s2);
// Check equality
System.out.println("set1 equals set2?: "
+ s1.equals(s2));
System.out.println("Set1: " + s1);
System.out.println("Set3: " + s3);
// Check equality
System.out.println("set1 equals set3?: "
+ s1.equals(s3));
}
}
Output
Set1: [1, 2, 3] Set2: [1, 2, 3] set1 equals set2?: true Set1: [1, 2, 3] Set3: [1, 2, 4] set1 equals set3?: false