![]() |
VOOZH | about |
How HashSet works internally in Java?
๐ How Set/HashSet works internally in Javab1 = true b2 = true b3 = false [GeeksforGeeks, Geeks]Now from the output, it is clear that when we try to add a duplicate element to a set using add() method, it returns false, and element is not added to hashset, as it is already present. Now the question comes, how add() method checks whether the set already contains the specified element or not. It will be more clear if we have a closer look on the add() method and default constructor in HashSet class.
// predefined HashSet class
public class HashSet
{
// A HashMap object
private transient HashMap
Now as you can see that whenever we create a HashSet, it internally creates a HashMap and if we insert an element into this HashSet using add() method, it actually call put() method on internally created HashMap object with element you have specified as itโs key and constant Object called "PRESENT" as itโs value. So we can say that a Set achieves uniqueness internally through HashMap. Now the whole story comes around how a HashMap and put() method internally works.
As we know in a HashMap each key is unique and when we call put(Key, Value) method, it returns the previous value associated with key, or null if there was no mapping for key. So in add() method we check the return value of map.put(key, value) method with null value.