How HashSet works in Java

By | 2017-05-22T06:15:42+05:30 May 12th, 2015|java|

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

HashSet in Java

HashSet Java

The underlying datastructure 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 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 a value to HashSet, the add() method internally put the given value as a key in the underlaying 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 same. The Hash Set doesn’t guarantee the insertion order. Based on the hash code of the values, the order is confirmed.

Key Points

[tie_list type=”checklist”]

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

[/tie_list]

Trying to add duplicate element in HashSet

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

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("is allow duplicates. ? " + set.add("Y"));
        System.out.println("Values : " + set);
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]
is allow duplicates. ? false
Values : [null, A, 2, X, Y, Z]

[/box]

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

3 Comments

  1. chagantirajesh.cultuzz@gmail.com'
    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. kishore.smsk@gmail.com'
    Nani June 17, 2016 at 4:54 pm - Reply

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

    • 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.

      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);
      		}
      	}
      }
      

Leave A Comment