In Java, the equals() method of the Set class is used to compare two sets for equality. It checks if two sets contain the same elements regardless of their order.
Example 1: This example demonstrates how to compare two HashSet collections for equality of type string using the equals() method.
// Java program to demonstrate
// the working of equals() method
import java.util.*;
public class Geeks {
public static void main(String[] argv)
{
// Creating object of Set
Set<String> s1 = new HashSet<String>();
s1.add("A");
s1.add("B");
s1.add("C");
s1.add("D");
s1.add("E");
System.out.println("First Set: " + s1);
// Creating another object of Set
Set<String> s2 = new HashSet<String>();
s2.add("A");
s2.add("B");
s2.add("C");
s2.add("D");
s2.add("E");
System.out.println("Second Set: " + s2);
// comparing first Set to another
// using equals() method
boolean value = s1.equals(s2);
System.out.println("Are both set equal? " + value);
}
}
Output
First Set: [A, B, C, D, E] Second Set: [A, B, C, D, E] Are both set equal? true
Syntax of equals() Method
boolean equals(Object o)
- Parameter: This method takes an object as a parameter.
- Return Type: This method returns "true" if the two sets are equal, otherwise it returns "false".
Example 2: This example demonstrates how to compare two HashSet collections for equality of type integer using the equals() method.
// Java Program to demonstrates
// the working of equals() method
import java.util.*;
public class Geeks {
public static void main(String[] argv)
{
// Creating object of Set
Set<Integer> s1 = new HashSet<Integer>();
s1.add(10);
s1.add(20);
s1.add(30);
s1.add(40);
s1.add(50);
System.out.println("First Set: " + s1);
// Creating another object of Set
Set<Integer> s2 = new HashSet<Integer>();
s2.add(10);
s2.add(20);
s2.add(30);
System.out.println("Second Set: " + s2);
// comparing first Set to another
// using equals() method
boolean value = s1.equals(s2);
System.out.println("Are both set equal? " + value);
}
}
Output
First Set: [50, 20, 40, 10, 30] Second Set: [20, 10, 30] Are both set equal? false