What is the HashSet.equals() method in Java?
The HashSet.equals() method is present in the HashSet class inside the java.util package. It is used to check the equality between the two objects of a HashSet irrespective of the order of elements present in them.
Let’s understand this with the help of some examples:
-
Suppose the first HashSet contains [1, 8, 5, 3, 0] and the second HashSet contains [8, 5, 0, 3, 1]. The first HashSet contains the same elements as in the second HashSet. So,
HashSet.equals()will return true. -
Now, suppose that the first HashSet contains [1, 6, 5, 9, 3, 2] and the second HashSet contains [1, 4, 6, 3, 7, 9]. The first HashSet doesn’t contain the same elements as the second HashSet. So,
HashSet.equals()will return false.
Parameters
The HashSet.equals() method takes one parameter called object. It is the object of type HashSet that needs to be compared for equality with another object.
Return value
The HashSet.equals() method returns a Boolean value.
- A return value of
trueindicates that the two HashSet objects are equal. - A return value of
falseindicates that the two HashSet objects are not equal.
Code
Let’s have a look at the code.
import java.io.*;import java.util.HashSet;class Main{public static void main(String args[]){HashSet<Integer> hash_set1 = new HashSet<Integer>();hash_set1.add(1);hash_set1.add(8);hash_set1.add(5);hash_set1.add(3);hash_set1.add(0);HashSet<Integer> hash_set2 = new HashSet<Integer>();hash_set2.add(1);hash_set2.add(0);hash_set2.add(8);hash_set2.add(3);hash_set2.add(5);HashSet<Integer> hash_set3 = new HashSet<Integer>();hash_set3.add(1);hash_set3.add(7);hash_set3.add(5);hash_set3.add(2);hash_set3.add(8);System.out.println("hash_set1 is equal to hash_set2? : " + hash_set1.equals(hash_set2));System.out.println("hash_set2 is equal to hash_set3? : " + hash_set2.equals(hash_set3));}}
Explanation
-
In lines 1 and 2, we import the required packages and classes.
-
In line 4, we created the
Mainclass. -
In line 6, we created the
main()function. -
In line 8, we declare a HashSet of Integer type i.e.
hash_set1. -
From lines 9 to 13, we add the elements into the HashSet by using the
HashSet.add()method. -
In line 15, we declare a HashSet of Integer type i.e.
hash_set2. -
In lines 16 to 20, we add the elements into the HashSet by using the
HashSet.add()method. -
In line 22, we declare a
HashSetof Integer type i.e.hash_set3. -
In lines 23 to 27, we add the elements into the HashSet by using the
HashSet.add()method. -
In line 29, we display the result whether
hash_set1is equal tohash_set2by using theHashSet.equals()method with a message. -
In line 31, we display the result whether
hash_set2is equal tohash_set3by using theHashSet.equals()method with a message.