HashSet Internal Working : How HashSet ensure Uniqueness

HashSet is an implementation of Set interface in Java which means in Set duplicate elements can not be added. If we try to add duplicate element then HashSet will discard the newly duplicated element to be added. But the question is How HashSet does that , How does it find out about the duplicate element and discard it from getting added.

Let's see the internal working of HashSet to find the asnwer.

When you open the HashSet implementation of the add() method in Java Apis that is rt.jar , you will find the following code in it.

So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

As we know in HashMap each key is unique . So what we do in the set is that we pass the argument in the add(Elemene E) that is E as a key in the HashMap . Now we need to associate some value to the key , so what Java apis developer did is to pass the Dummy  value that is ( new Object () ) which is referred by Object reference PRESENT .

Now if you see the code of the HashMap put(Key k,Value V) method , you will find something like this

public V put(K key, V value) {
     //Some code
}
The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value i.e.
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
So , if map.put(key,value) returns null ,then  map.put(e, PRESENT)==null  will return true and element is added to the HashSet.

So , if map.put(key,value) returns old value of the key ,then map.put(e, PRESENT)==null  will return false and element is  not added to the HashSet .

This covers the concept of internal working of HashSet , if you have any questions or you want to add anything then please comment below.

Comments

Popular posts from this blog

Deploy standalone Spring MVC Application in Docker Container

Refactor Code : Separate Query from Modifier

HTTP : Must known Protocol (Part 1)