The equals() method of java.util.LinkedHashSet class is used to compare the specified object with this set for equality. Returns true if and only if the specified object is also a set, both sets have the same size, and all corresponding pairs of elements in the two sets are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two sets are defined to be equal if they contain the same elements in any 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 examples to illustrate the equals() method.
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv)
{
LinkedHashSet<String> set1
= new LinkedHashSet<String>();
set1.add( "A" );
set1.add( "B" );
set1.add( "C" );
set1.add( "D" );
set1.add( "E" );
System.out.println( "First LinkedHashSet: " + set1);
LinkedHashSet<String> set2
= new LinkedHashSet<String>();
set2.add( "A" );
set2.add( "B" );
set2.add( "C" );
set2.add( "D" );
set2.add( "E" );
System.out.println( "Second LinkedHashSet: " + set2);
boolean value = set1.equals(set2);
System.out.println( "Are both set equal: " + value);
}
}
|
Output:
First LinkedHashSet: [A, B, C, D, E]
Second LinkedHashSet: [A, B, C, D, E]
Are both set equal: true
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
LinkedHashSet<Integer>
set1 = new LinkedHashSet<Integer>();
set1.add( 10 );
set1.add( 20 );
set1.add( 30 );
set1.add( 40 );
set1.add( 50 );
System.out.println("First LinkedHashSet: "
+ set1);
LinkedHashSet<Integer>
set2 = new LinkedHashSet<Integer>();
set2.add( 10 );
set2.add( 20 );
set2.add( 30 );
System.out.println("Second LinkedHashSet: "
+ set2);
boolean value = set1.equals(set2);
System.out.println("Are both set equal: "
+ value);
}
}
|
Output:
First LinkedHashSet: [10, 20, 30, 40, 50]
Second LinkedHashSet: [10, 20, 30]
Are both set equal: false
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!