The HashSet.remove()
method is present in the HashSet
class inside the java.util
package. The HashSet.remove()
method is used to remove only the specified element from the HashSet
.
Let’s understand with the help of an example.
Suppose that the Hashset
contains the following: [1, 8, 5, 3, 0]
. We execute the below statements on this hashset:
Hashset1.remove(8);
Hashset1.remove(0);
After using the remove()
method, the HashSet
contains [1, 5, 3]
.
public boolean remove(Object obj)
The HashSet.remove()
accepts one parameter:
obj
: The Object
of HashSet
type that needs to be removed from the HashSet
.The HashSet.remove()
method returns true
if the HashSet
gets changed as a result of the call to the method.
Let’s have a look at the code now.
import java.io.*;import java.util.HashSet;class Main{public static void main(String args[]){HashSet<Integer> hash_set1 = new HashSet<Integer>();hash_set1.add(1);hash_set1.add(8);hash_set1.add(5);hash_set1.add(3);hash_set1.add(0);System.out.println("hash_set1 before calling remove(): "+ hash_set1);boolean removeVal1;boolean removeVal2;removeVal1 = hash_set1.remove(150);removeVal2 = hash_set1.remove(8);System.out.println("hash_set1 after calling remove(): "+ hash_set1);System.out.println("the removal of 8 was: " + removeVal2);System.out.println("the removal of 150 was: " + removeVal1);}}
HashSet
of integer type, i.e., hash_set1
.HashSet
by using the HashSet.add()
method.HashSet
before calling the remove()
method.remove()
function to remove specific elements from the HashSet
and assign the returned values to boolean variables.150
is passed as the argument, nothing happens, as it is not present. But when 8
is removed, the change is reflected.HashSet
after calling the remove()
method.remove()
method are displayed.