Member-only story
How HashSet Works Internally In Java?
As we know set will never contain duplicate elements.
But how in java Set interface implemented class HashSet achieve this uniqueness. In this post, we will discuss about this.
HashSet uses HashMap internally to store it’s objects. Every constructor of HashSet class internally creates one HashMap object.
/**
* Constructs a new, empty set; the backing HashMap instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
Whenever you create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements you enter in the HashSet.
import java.util.HashSet;
import java.util.Set;public class Test {
public static void main(String[] args) {Set<String> channel = new HashSet<>();
boolean res1 = channel.add(“gain”);
boolean res2 = channel.add(“java”);
boolean res3 = channel.add(“java”);
boolean res4 = channel.add(“knowledge”);System.out.println(“res1 : “ + res1); // res1 : true
System.out.println(“res2 : “ + res2); // res2 : true
System.out.println(“res3 : “ + res3); // res3 : false
System.out.println(“res4 : “ + res4); // res4 : trueSystem.out.println(channel); //[java, gain, knowledge]
}
}
Now from the output, it is clear that when we try to add a duplicate element to a set using add() method, it…