- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check whether two HashSet are equal in Java
At first, create the first HashSet and add elements to it −
// create hash set 1 HashSet hs1 = new HashSet(); hs1.add("G"); hs1.add("H"); hs1.add("I"); hs1.add("J"); hs1.add("K");
Create the second HashSet and add elements to it −
// create hash set 2 HashSet hs2 = new HashSet(); hs2.add("G"); hs2.add("H"); hs2.add("I"); hs2.add("J"); hs2.add("K");
To check whether both the HashSet are equal or not, use the equals() method −
hs1.equals(hs2)
The following is an example to check whether two HashSet are equal −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // create hash set 1 HashSet hs1 = new HashSet(); hs1.add("G"); hs1.add("H"); hs1.add("I"); hs1.add("J"); hs1.add("K"); System.out.println("Elements in set 1 = "+hs1); // create hash set 2 HashSet hs2 = new HashSet(); hs2.add("G"); hs2.add("H"); hs2.add("I"); hs2.add("J"); hs2.add("K"); System.out.println("Elements in set 2 = "+hs2); System.out.println("Are both the HashSet equal? "+hs1.equals(hs2)); } }
Output
Elements in set 1 = [G, H, I, J, K] Elements in set 2 = [G, H, I, J, K] Are both the HashSet equal? True
Advertisements