Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

In java how does HasSet enures unique values?

Let us discuss on how the HashSet in java prevents adding the duplicate values. First let us understand how to create a HashSet and add some values to it.

public class HashSetTest{
    
    public static void main(String[] args)
    {
        HashSet<String> hashset = new HashSet>();
        hashset.add("Bangalore");
        hashset.add("Mysore");
        hashset.add("Hubli");
        System.out.println("Set is "+hashset);
    }
} 


Output would be : Hubli, Bangalore,Mysore

What about the insertion order in the above output? Does the insertion order not maintained? Yes in a HashSet the insertion order is not maintained also the values in a HashSet are not sorted.

Now to the above code let us try to add some duplicates as below:

public class HashSetTest{
    
    public static void main(String[] args)
    {
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add("Bangalore");
        hashset.add("Hubli");
        hashset.add("Mysore");
        hashset.add("Hubli");          // duplicate elements
        hashset.add("Bangalore");      // duplicate elements
        System.out.println("Set is "+hashset);
    }
}

Now the output would be: Bangalore, Mysore, Hubli
Did you notice add() method of HashSet ignored the duplicates? Now the question is how?
When you pass duplicate elements in the  add() method of the Set object, It will return false and do not add to the HashSet, as the element is already present.

Let us go into further deep:


public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
    private transient HashMap<E,Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    
    
    public HashSet() {
        map = new HashMap<>();
    }
    
    // SOME CODE ,i.e Other methods in Hash Set
      
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }  
    
    // SOME CODE ,i.e Other methods in Hash Set
}

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 .