Thursday, December 12, 2019

How Hashset Internally Industrial Plant Inwards Java

Not many programmer know that HashSet is internally implemented using HashMap in Java, hence if you lot know How HashMap industrial plant internally inwards Java, to a greater extent than probable you lot tin figure out how HashSet industrial plant inwards Java. But, at nowadays a curious Java developer tin enquiry that, how come upward HashSet uses HashMap, because you lot request a key value twain to usage amongst Map, spell inwards HashSet we alone shop ane object. Good question, isn't it? If you lot recall to a greater extent than or less functionality of before class, in addition to hence you lot know that HashMap allows duplicate values in addition to this belongings is exploited spell implementing HashSet inwards Java. Since HashSet implements Set interface it needs to guarantee uniqueness in addition to this is achieved past times storing elements every bit keys amongst same value always. Things gets clear past times checking HashSet.java from JDK root code. All you lot request to await at is, how elements are stored inwards HashSet in addition to how they are retrieved from HashSet. Since HashSet doesn't supply whatever right away method for retrieving object e.g. get(Key key) from HashMap or get(int index) from List, alone agency to acquire object from HashSet is via Iterator. See here for code representative of iterating over HashSet inwards Java. When you lot exercise an object of HashSet inwards Java, it internally exercise event of backup Map amongst default initial capacity sixteen in addition to default charge cistron 0.75 every bit shown below :

/**
  * Constructs a new, empty set; the backing <tt>HashMap</tt> event has   * default initial capacity (16) in addition to charge cistron (0.75).   */  populace HashSet() {    map = new HashMap<>(); }

Now let's run into the code for add() in addition to iterate() method from java.util.HashSet inwards Java to sympathise how HashSet industrial plant internally inwards Java.



How Object is stored inwards HashSet
As you lot tin run into below, a telephone outcry upward to add(Object) is delegate to put(Key, Value) internally, where Key is the object you lot bring passed in addition to value is to a greater extent than or less other object,  called PRESENT, which is a constant inwards java.util.HashSet every bit shown below :

private transient HashMap<E,Object> map;  // Dummy value to associate amongst an Object inwards the backing Map private static final Object PRESENT = new Object();  populace boolean add(E e) {    return map.put(e, PRESENT)==null; }

Since PRESENT is a constant, for all keys nosotros bring same value inwards backup HashMap called map.


How Object is retrieved from HashSet
Now let's run into the code for getting iterator for traversing over HashSet inwards Java. iterator() method from java.util.HashSet class returns iterator for backup Map returned past times map.keySet().iterator() method.

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

How to usage HashSet inwards Java

Using HashSet in Java is rattling simple, don't mean value it is Map but mean value to a greater extent than similar Collection i.e. add together elements past times using add() method, cheque its render value to run into if object already existed inwards HashSet or not. Similarly usage iterator for retrieving chemical cistron from HashSet in Java. You tin too usage contains() method to cheque if whatever object already exists inwards HashSet or not. This method usage equals() method for comparison object for matching. You tin too usage remove() method to take object from HashSet. Since chemical cistron of HashSet is used every bit key inwards backup HashMap, they must implement equals() in addition to hashCode() method. Immutability is non requirement exactly if its immutable in addition to hence you lot tin assume that object volition non live on changed during its rest on set. Following representative demonstrate basic usage of HashSet in Java, for to a greater extent than advanced example, you lot tin cheque this tutorial.    

import java.util.HashSet; import java.util.Iterator;   /**  * Java Program to demonstrate How HashSet industrial plant internally inwards Java.  * @author http://java67.blogspot.com  */  public class HashSetDemo{          public static void main(String args[]) {        HashSet<String> supportedCurrencies = new HashSet<String>();                      // adding object into HashSet, this volition live on translated to put() calls       supportedCurrencies.add("USD");       supportedCurrencies.add("EUR");       supportedCurrencies.add("JPY");       supportedCurrencies.add("GBP");       supportedCurrencies.add("INR");       supportedCurrencies.add("CAD");        // retrieving object from HashSet       Iterator<String> itr = supportedCurrencies.iterator();       while(itr.hasNext()){          System.out.println(itr.next());        }    }  }  Output JPY EUR INR USD CAD GBP

That's all close How HashSet is implemented inwards Java in addition to How HashSet industrial plant internally. As I said, If you lot how HashMap internally inwards Java, you lot tin explicate working of HashSet provided,  you know it uses same values for all keys. Remember to override equals() in addition to hashCode() for whatever object you lot are going to shop inwards HashSet, since your object is used every bit key inwards backup Map, it must override those method. Make your object Immutable or effective immutable if possible.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java
Algorithms in addition to Data Structures - Part 1 in addition to ii
Data Structures inwards Java ix past times Heinz Kabutz


No comments:

Post a Comment