The AbstractSet.equals() method in Java AbstractSet is used to check for equality between two sets. It verifies whether the elements of one set passed as a parameter is equal to the elements of this set or not.
Syntax:
AbstractSet1.equals(AbstractSet2)
Parameters: The method accepts one parameter AbstractSet2 of abstract set type and refers to the set whose equality is to be checked with this abstract set.
Return Value: The method returns true if the equality holds for both the object set else it returns false.
Below programs illustrate the working of AbstractSet.equals() method:
Program 1:
// Java code to illustrate the equals() method import java.util.*;
public class Abstract_Set_Demo {
public static void main(String[] args)
{
// Creating an empty AbstractSet
AbstractSet<String>
abstract_set1 = new HashSet<String>();
AbstractSet<String>
abstract_set2 = new HashSet<String>();
// Adding elements to set
abstract_set1.add( "Geeks" );
abstract_set1.add( "4" );
abstract_set1.add( "Geeks" );
abstract_set1.add( "Welcomes" );
abstract_set1.add( "You" );
// Adding elements to set
abstract_set2.add( "Geeks" );
abstract_set2.add( "4" );
abstract_set2.add( "Geeks" );
abstract_set2.add( "Welcomes" );
abstract_set2.add( "You" );
// Displaying the first HashSet
System.out.println( "First Set: "
+ abstract_set1);
// Displaying the second HashSet
System.out.println( "Second Set: "
+ abstract_set2);
// Displaying the equality
System.out.println( "Equality: "
+ abstract_set1
.equals(abstract_set2));
}
} |
First Set: [4, Geeks, You, Welcomes] Second Set: [4, Geeks, You, Welcomes] Equality: true
Program 2:
// Java code to illustrate the equals() method import java.util.*;
public class Abstract_Set_Demo {
public static void main(String[] args)
{
// Creating an empty AbstractSet
AbstractSet<String>
abstract_set1 = new HashSet<String>();
AbstractSet<String>
abstract_set2 = new HashSet<String>();
// Adding elements to set
abstract_set1.add( "Geeks" );
abstract_set1.add( "4" );
abstract_set1.add( "Geeks" );
abstract_set1.add( "Welcomes" );
abstract_set1.add( "You" );
// Adding elements to set
abstract_set2.add( "Geeks" );
abstract_set2.add( "4" );
abstract_set2.add( "Geeks" );
abstract_set2.add( "Welcomes" );
abstract_set2.add( "U" );
// Displaying the first HashSet
System.out.println( "First Set: "
+ abstract_set1);
// Displaying the second HashSet
System.out.println( "Second Set: "
+ abstract_set2);
// Displaying the equality
System.out.println( "Equality: "
+ abstract_set1
.equals(abstract_set2));
}
} |
First Set: [4, Geeks, You, Welcomes] Second Set: [4, U, Geeks, Welcomes] Equality: false