Java HashSet class

A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

Main Important Point

  • HashSet provides collection of unique objects
  • HashSet is unsorted, unordered and non-indexed based collection class
  • HashSet can have only one Null element

Difference between List and Set:

List can contain duplicate elements whereas Set contains unique elements only

HashSet Methods

Sn Method Purpose
1 public boolean add(Object o) Adds an object to a HashSet if already not present in HashSet
2 public boolean remove(Object o) Removes an object from a HashSet if found in HashSet.
3 public boolean contains(Object o) Returns true if object found else return.
4 public boolean isEmpty() Returns true if HashSet is empty else return false .
5 public int size() Returns number of elements in the HashSet .

Example of HashSet class:

import java.util.HashSet;

public class HashSetDemo


public static void main(String[] args)


HashSet hs = new HashSet();

// Adding element to HashSet







System.out.println("Size of HashSet=" + hs.size());

System.out.println("Original HashSet:" + hs);

System.out.println("Removing A from HashSet: " + hs.remove("A"));

System.out.println("Trying to Remove Z which is not present: "+ hs.remove("Z"));

System.out.println("Checking if M is present=" + hs.contains("M"));

System.out.println("Updated HashSet: " + hs);

}	}



Size of HashSet=5

Original HashSet:[A, B, C, M, X]

Removing A from HashSet: true

Trying to Remove Z which is not present: false

Checking if M is present=true

Updated HashSet: [B, C, M, X]

Press any key to continue . . .