java.util.HashSet isEmpty()
Description
The HashSet as majority of the Collection classes make use of Generics such that if we have declared our set like HashSet set = new HashSet() then the elements of inside our set is of type String. And we cannot insert different object type not unless its a subclass of the object declaration, otherwise a runtime error will be thrown.
The HashSet elements are unique, there would be no two identical elements that can exist.
Important notes for isEmpty() method:
- specified by isEmpty in interface Collection
- specified by isEmpty in interface Set
- overrides isEmpty in class AbstractCollection
Method Syntax
public boolean isEmpty()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The isEmpty() method returns true if this set contains no elements.
Compatibility
Requires Java 1.2 and up
Java HashSet isEmpty() Example
Below is a java code demonstrates the use of isEmpty() method of HashSet class. The example presented might be simple however it shows the behavior of the isEmpty() method.
package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashSet; /* * This example source code demonstrates the use of * isEmpty() method of HashSet class */ public class HashSetIsEmptyExample { public static void main(String[] args) throws InterruptedException { // get the HashMap object from the method init() HashSet studentSet = init(); // validate the contents of our set if(studentSet.isEmpty()){ out.println("student database is empty"); } else{ out.println("student database has "+studentSet.size()+" names"); } } private static HashSet init() { // declare the HashSet object HashSet studentSet = new HashSet<>(); // put contents to our HashMap studentSet.add("Shyra Travis"); studentSet.add("Sharon Wallace"); studentSet.add("Leo Batista"); return studentSet; } }
There are two methods created on the above example, main() and init. The main method calls the init() which initializes and assign values to a HashSet object. The main() method assign to a new HashSet object the returned object by the init() method. We use the isEmpty method to validate our HashSet if its empty or not.