This Java Example shows how to remove a specified object or element contained in Java HashSet object using remove method.
import java.util.HashSet;
public class RemoveSpecifiedElementFromHashSetExample {
 public static void main(String[] args) {
  // create object of HashSet
  HashSet hSet = new HashSet();
  // add elements to HashSet object
  hSet.add(1);
  hSet.add(2);
  hSet.add(3);
  System.out.println("HashSet before removal : " + hSet);
  /**
   * To remove an element from Java HashSet object use, boolean
   * remove(Object o) method. This method removes an element from HashSet
   * if it is present and returns true. Otherwise remove method returns
   * false.
   **/
  boolean blnRemoved = hSet.remove(2);
  System.out.println("Was 2 removed from HashSet ? " + blnRemoved);
  System.out.println("HashSet after removal : " + hSet);
 }
}
The output is:
HashSet before removal : [1, 2, 3]
Was 2 removed from HashSet ? true
HashSet after removal : [1, 3]
No comments:
Post a Comment