As we have seen the implementations of a Set are :
Let us see the HashSet implementation,
Let us say, we have a HashSet that contains three names, Mohan, Kriti and Salim. And we want to remove Kriti from the HashSet.
It can be done with the Remove() method.
import java.util.*; public class MyApplication { public static void main(String[] args) { Setx = new HashSet<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.remove("Kriti"); for (String i : x) { System.out.println(i); } } }
So, in the above code we have created a HashSet and initialised to the variable x.
Setx = new HashSet<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the HashSet,
Next, we have used the remove() method that searches for the name Kriti and removes it from the HashSet.
x.remove("Kriti")
And we get the below output,
The clear() Method can be used to remove all the elements from the HashSet.
import java.util.*; public class MyApplication { public static void main(String[] args) { Setx = new HashSet<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.clear(); for (String i : x) { System.out.println(i); } } }
So, in the above code we have created a HashSet and initialised to the variable x.
Setx = new HashSet<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the HashSet,
Next, we have used the clear() method that removes all the elements from the HashSet making the HashSet empty.
And we get an empty HashSet as output.
import java.util.*; public class MyApplication { public static void main(String[] args) { Setx = new LinkedHashSet<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); x.clear(); for (String i : x) { System.out.println(i); } } }