Java Collection Framework provides a set of interfaces and implemented classes. The HashSet in Java is a direct implementation of the Set interface, which provides the functionality to store the collection of Objects.

HashSet in Java

HashSet Java

The underlying data structure of the HashSet is a Hash Map. When we create a HashSet Object, It internally creates a new empty Set with the backing HashMap instance.

The HashMaps’s initial capacity is 16, and the load factor is 0.75.

Source code for HashSet constructor.


public HashSet() {
        map = new HashMap<E, Object>();
    }

Usually, Hash Map is a Collection, which stores the data as key-value pairs. But in the HashSet, we are going to insert only values by using the add() method. When we add value to HashSet, the add() method internally put the given value as a key in the underlying hash map and assign the dummy object as a value, hence the HashSet doesn’t allow the duplicate values.

Below is the add() method source code for understanding.

public Boolean add(E e) {        
      return map.put(e, dummy_object) == null;     
}

Example:

public class HashSetDemo {    
    public static void main(String[] args) {       
        Set set = new java.util.HashSet();       
        set.add("X");        
        set.add("Y");       
        set.add("Z");       
        set.add("A");        
        set.add(2);       
        set.add(null);        
        System.out.println("set : " + set);   
    }
}

Output:

Values : [null, 2, A, Y, X, Z]

On the above output, if we observe closely, the insertion order is not the same. The Hash Set doesn’t guarantee the insertion order. Based on the hash code of the values, the order is confirmed.

Key Points

  • Hash Set doesn’t allow duplicate values.
  • Hash Set doesn’t maintain insertion order.
  • Hash Set accepts the various data elements.
  • The initial capacity of the Hash Set is 16.
  • The load factor of Hash Set is 0.75.
  • Hash Set is recommended to repeated CRUD operations.

Trying to add the duplicate element in HashSet

When we try to insert a duplicate item to HashSet, it doesn’t throw any exception or error.
In the case of a duplicate, insertion add() method returns the “false”.

Example:

HashSetDemo.java
public class HashSetDemo {
    public static void main(String[] args) {
        Set set = new java.util.HashSet();
        set.add("X");
        set.add("Y");
        set.add("Z");
        set.add("A");
        set.add(2);
        set.add(null);
        System.out.println("is allow duplicates. ? " + set.add("Y"));
        System.out.println("Values : " + set);
    }
}

Output:

Termminal
is allow duplicates. ? false
Values : [null, A, 2, X, Y, Z]

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

3 Comments

  1. Avatar
    rajesh chaganti May 13, 2015 at 5:32 pm - Reply

    Excellent & Valuable post….It clears all of my doubts regarding hashmap and hashset..I am learning a lot from your experienced posts….keep posting…..

  2. Avatar
    Nani June 17, 2016 at 4:54 pm - Reply

    Can you please explain how to retrieve/iterate heterogeneous data from hash set.

    • Avatar
      chandrashekhar June 18, 2016 at 2:43 am - Reply

      Hi Nani,

      Heterogeneous collection means, we can store dissimilar objects or classes in an collection. In our case HashSet is a Heterogeneous type collection. Here is the example for HashSet with Heterogeneous elements.
      [sourcecode language=”java”]
      import java.util.HashSet;
      import java.util.Iterator;
      import java.util.Set;

      public class HashSetExample {
      public static void main(String args[]){
      Set set = new HashSet();
      // Integer type
      set.add(new Integer("20"));
      // String type
      set.add("123456");
      // object type
      set.add(new Object());

      Iterator iterator = set.iterator();
      while (iterator.hasNext()) {
      Object object = (Object) iterator.next();
      System.out.println(object);
      }
      }
      }
      [/sourcecode]

Leave A Comment