Secrets of HashSet Collection :

 HashSet is data structures that let you find elements much faster. The drawback is that those data structures give you no control over the order in which the elements appear. It uses hash table, A hash table computes an integer, called the hash code, for each object. A hash code is an integer that is somehow derived from the instance fields of an object, preferably such that objects with different data yield different codes.

In Java, hash tables are implemented as arrays of linked lists. Each list is called a bucket. To find the place of an object in the table, compute its hash code and reduce it modulus the total number of buckets.

LoadFactor:  The load factor determines when a hash table is rehashed. For example, if the load factor is 0.75 (which is the default) and the table is more than 75% full, then it is automatically rehashed, with twice as many buckets.



Internal architecture of HashSet :


This class implements the Set interface, backed by a hash table (actually a HashMap instance). It uses HashMap object internally in constructor.

private transient HashMap<E,Object> map;

public HashSet() {

map = new HashMap<E,Object>();
}


Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75). There are four more constructors of HashSet.




 It internally uses HashMap methods. See below

public boolean add(E e) {return map.put(e, PRESENT)==null;   //calls put method of Map

}


0 comments:

Post a Comment

 
Copyright (c) 2013 Java Discovery.