HashSet overview

HashSet is a java class which implements Set interface

Main features of HashSet


HashSet contains only unique elements, does not allow duplicates.

HashSet stores elements by using “hashing” mechanism

It does not maintain the insertion order, elements will be in random order.

It allows null value, since it allows unique values, only one null value is allowed

It is non-synchronized Set by default, however we can synchronize it using Collections utility

We can create HashSet using constructor as below

  1. HashSet<String>  hs = new HashSet<String>();
HashSet<String>  hs = new HashSet<String>();


Example :

  1. import java.util.HashSet;
  2. public class HashSetExample {
  3.    public static void main(String args[]) {
  4.      
  5.       HashSet<String> hs =  new HashSet<String>();
  6.  
  7.       hs.add("java");
  8.       hs.add("c");
  9.       hs.add("c++");
  10.       //Adding duplicate elements
  11.       hs.add("java");
  12.       hs.add("c++");
  13.       //Adding null values
  14.       hs.add(null);
  15.       hs.add(null);
  16.  
  17.       //Displaying HashSet elements
  18.       System.out.println(hs);
  19.     }
  20. }
import java.util.HashSet;
public class HashSetExample {
   public static void main(String args[]) {
     
      HashSet<String> hs =  new HashSet<String>();

      hs.add("java");
      hs.add("c");
      hs.add("c++");
      //Adding duplicate elements
      hs.add("java");
      hs.add("c++");
      //Adding null values
      hs.add(null);
      hs.add(null);

      //Displaying HashSet elements
      System.out.println(hs);
    }
}
Note : We can observe in the output that, duplicate elements are not present including Null duplicate value.

When to use HashSet ?

HashSet should be used whenever We want to store only unique elements in a collection and We are not interested to maintain the order of insertion

When not use HashSet ?

HashSet should not be used whenever We need to allow duplicate elements and We need to maintain the insertion order within the collection

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on