This Java Example shows how to remove all elements exists in HashSet.
clear in Java HashSet Example
This Java Example shows how to remove all elements exists in HashSet. To remove all the elements exists in HashSet We use clear() method of HashSet class. It removes all the elements stored in the specified object within the collection. To check that specified HashSet object is empty or not we use boolean isEmpty() method of the HashSet class. This method returns true if the object is empty otherwise returns false.
Example:- RemoveAllInHashSet.java
package devmanuals.com; import java.util.HashSet; public class RemoveAllInHashSet { public static void main(String[] args) { HashSet hst = new HashSet(); hst.add("Gyan"); hst.add("Rohit"); hst.add("Anand"); hst.add("Arunesh"); System.out.println("The Elements are: " + hst); hst.clear(); boolean b2 = hst.isEmpty(); System.out.println("The Hash Set is Empty :" + b2); System.out.println("The Elements after removal: " + hst); } }
Output:-
The Elements are: [Rohit, Gyan, Arunesh, Anand]
The Hash Set is Empty : true The Elements after removal: [] |
[ 0 ] Comments