java.util.HashSet remove(Object o)
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 remove() method:
- specified by remove in interface Collection<E>
- specified by remove in interface Set<E>
- overrides remove in class AbstractCollection<E>
Method Syntax
public boolean remove(Object o)
Method Argument
Data Type | Parameter | Description |
---|---|---|
Object | o | element to be removed to this set if it is present |
Method Returns
The remove(Object o) method returns true if the set contained the specified element.
Compatibility
Requires Java 1.2 and up
Java HashSet remove() Example
Below is a java code demonstrates the use of remove() method of HashSet class. The example presented might be simple however it shows the behavior of the remove() method.
package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashSet; /* * This example source code demonstrates the use of * remove() method of HashSet class */ public class HashSetRemoveExample { public static void main(String[] args) throws InterruptedException { // get the HashMap object from the method init() HashSet studentSet = init(); // remove an element boolean result = studentSet.remove("Sharon Wallace"); if (result) { out.println("Element successfully removed"); } else { out.println("Element were not present"); } // remove an element that is not present result = studentSet.remove("Darwin Ingram"); if (result) { out.println("Element successfully removed"); } else { out.println("Element were not present"); } } 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. An element were tried to be removed to the set by calling the remove() method. Based on the returned value, we have evaluated if the removal is successful or not. If the result is false, the element we are trying to remove is not present.