- 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 a HashSet is empty or not in Java
To check whether a HashSet is empty or not, use the isEmpty() method.
Create a HashSet −
HashSet hs = new HashSet();
Add elements to the HashSet −
hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M"); hs.add("N");
Now, check whether the HashSet is empty or not. Since we added elements above, it won’t be empty −
hs.isEmpty();
The following is an example that checks whether a HashSet is empty or not −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M"); hs.add("N"); System.out.println("Elements: "+hs); System.out.println("Is the set empty? = "+hs.isEmpty()); } }
Output
Elements: [A, B, C, D, E, F, K, M, N] Is the set empty? = false
Let us see another example −
Example
import java.util.*; public class Demo { public static void main(String args[]) { HashSet hs = new HashSet(); // empty set System.out.println("Is the set empty? = "+hs.isEmpty()); } }
Output
Is the set empty? = true
Advertisements