Mar 26, 2014

How HashSet works internally - Internal implementation

Internal implementation of any collection (HashMap, HashSet, LinkedhashMap, etc) is common interview question for senior java developer and it is highly recommended to brush-up internal implementations of collections before going for interview.Here I am discussing how HashSet works internally.Before reading this article you must know How HashMap works internally?, since HashMap is building block of internal working of HashSet.
Basic understanding of HashMap states that it stores key and value both in form of Map.Entry object. So our first befitting reply should be: "HashSet internally uses HashMap to store objects". HashSet constructor instantiate a HashMap when its constructor is being called. Below mentioned sample code from java.util.HashSet creates a HashMap named map.(Overloaded constructor of HashSet can be found here).
private transient HashMap<E,Object> map;
//Constructs a new, empty set; the backing HashMap instance 
//has default initial capacity (16) and load factor (0.75).
public HashSet() {
   map = new HashMap<E,Object>();
}
The very next question arises, since HashMap stores key/value pair while HashSet only stores object (set.add(someObject)) then "How Object is stored in HashSet":
Answer: HashMap stores object(Any value user is trying to store in set) as key and some pre-defined constant as value.By doing so, HashSet stores only unique values(Duplicate is not allowed).In other words, we call set.add(someObject) then call is redirected and map stores someObject as key and PRESENT(a constant) as value.Below mentioned sample code from java.util.HashSet, PRESENT is the the constatnt(marked final) value which is being used by HashMap.

// Dummy value to associate with an Object in the backing Map
 private static final Object PRESENT = new Object();
 //add operation 
 public boolean add(E e) {
   return map.put(e, PRESENT)==null; 
}
Please note the return type of add method is boolean: after adding object to map it is comparing with null, as it is expected( map will return the previous value associated with key, or null if there was no mapping for key).If returing true menas no previous element was there and it added successfully.
Similarly when we delete object form HashSet by using remove method, it redirects call to HashMap to remove object and return boolean based on object was removed or not.below is sample code for remove method:
public boolean remove(Object o) {
     return map.remove(o)==PRESENT;
  }
This is how HashSet works internally with the help of HashMap. Now try this question:
class TryHashSet{
 public static void main(String[] args) {
   HashSet<string> set = new HashSet();
   boolean stat1 = set.add("Topper of class");
   boolean stat2 = set.add("Second ranker");
   boolean stat3 = set.add("Topper of class");
   boolean stat4 = set.remove("Topper of class");
   boolean stat5 = set.remove("Topper of class");
   System.out.println(stat1 + " " + stat2 + " " +stat3 + " "+ stat4  + " " +stat5);
 }
}
Sample output : true true false true false

===============End of article==========================
Happy learning!!
Nikhil

Related post,you may like it:
1. Java puzzle - Set 1
2. Java puzzle - Set 2
Location: Hyderabad, Telangana, India

6 comments:

  1. Replies
    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.


      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.


      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete