Thursday, April 7, 2016

How Hashset works internally in java ?

Set and HashSet

Set in an interface , it does not allow duplicates. It can allow null value at only one time. 

Hashset implements Set Interface and It is not synchronized, so its not thread safe. It stores the object in random order. Hashset is much faster than TreeSet.

Hashset Example

HashSet set = new HashSet();
     set.add("test");
     set.add("test1");
     set.add(null);
     System.out.println("Values are" + set);

Output: Values are[null, test1, test]


To add the elements into Hashset, which is using HashMap internally
public class HashSet 
 extends AbstractSet
 implements Set, 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<>();
 }

 public boolean add(E e) {
     return map.put(e, PRESENT)==null;
    }
add(E e) method will be called after you add the element into set. If map.put(key,value) will return null, then condition will become true. Means, map.put(e,PRESENT) will return null (null ==null so TRUE). So element will be added.

Like same, If map.put(key,value) return old value of key, then condition will become false. Means, map.put(e,PRESENT)== null will return false (value!=null). So element will not be added. 

Here PRESENT is an dummy object reference and it will be used in map. 

No comments:

Post a Comment