272014Sep

HashSet Class in java

HashSet uses hash table to store the element it extends AbstractSet class and implements Set, Cloneable, java.io.Serializable.An object of this class is responsible to creating Hashtable (actually a HashMap instance) in memory and store element in Random manner with uniqueness.

Every Collection implements :- Cloneable, java.io.Serializable interface.

Four Constructor is available in HashSet-

1. HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
2. HashSet(Collection<? extends E> c)
Constructs a new set containing the elements in the specified collection.
3. HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
4. HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor

How to create Object of HashSet:-

HashSet hs =new HashSet();//HashSet without any element
HashSet hs1 =new HashSet(Arrays.asList(“apple”,”google”));//copying content
HashSet hs2 =new HashSet(50);//HashSet with initial capacity

Internal detail of default constructor:-

/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}

Features of HashSet:-

1. Data Structure :- HashSet is backed HashTable data structure.

2. We can insert Heterogeneous data ,unique data,multiple null value in HashSet.(Only TreeSet and TreeMap insert homogenous data in whole collection.)

3. Insertion in HashSet :- HashSet insertion order will not remain constant over time.HashSet uses add() method  to insert the elements in HashSet.If we are try to insert similar type of elements it return false.

HashSet hs=new HashSet();
hs.add("asknsay.com"); // add will return true
hs.add("asknsay.com"); // add will return false as Set already has

Internal Detail:-

HashSet add(Object) is internally call to put(Key, Value), where Key is the object you have passed and value is another object,called PRESENT, which is a constant in java.util.HashSet as shown below :

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 boolean add(E e) {
return map.put(e, PRESENT)==null;
}

Since PRESENT is a constant, for all keys we have same value in backup HashMap called map.

4. Traverse over HashSet:- For traversing over HashSet in Java. iterator() method from java.util.HashSet class returns iterator for backup Map returned by map.keySet().iterator() method.Iterating over this set requires time proportional to the sum of number of elements plus the number of buckets. Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator<E> iterator() {
return map.keySet().iterator();
}

5. Heterogeneous data:- We can add  Heterogeneous data in HashSet In whole Collection only TreeSet and TreeMap allow   homogeneous data because both collections are sorted,for sorting purpose somewhere we are overriding equals() method and with equals we can compare only similar type of data.

6.Capacity of HashSet:- HashSet initial capacity is 16 After this if we are adding value beyond the size of HashTable so by default it increase 0.75%  of a bucket ,it is called Load Factor its value must be between 0-1.

7 Synchronization
HashSet is not synchronized. It can not be shared between multiple threads, until specifically synchronized. We can create synchronized Set by using java.util.Collections utility class as shown below :

Synchronizing HashSet in Java

Set s = Collections.synchronizedSet(new HashSet(…));

Conclusion:-

  • HashSet will not guarantee that the order will remain constant over time.
  • HashSet provide constant time operation for basic function like add,remove,search,contain,size.
  • HashSet  class permits the null element.
  • Iterating over HashSet requires time proportional to the sum of the number of elements  plus the number of buckets.