How HashSet Internally Works in Java | Java67
Not many programmer know that
HashSet is internally implemented using
HashMap in Java, so if
you know How HashMap works internally in Java, more likely you can figure out
how HashSet works in Java. But, now a curious Java developer can question that, how come
HashSet uses
HashMap, because you need a key value pair to use with
Map, while in
HashSet we only store one object. Good question, isn't it? If you remember some functionality of earlier class, then you know that
HashMap allows duplicate values and this property is exploited while
implementing HashSet in Java. Since HashSet implements Set interface it needs to guarantee uniqueness and this is achieved by storing elements as keys with same value always. Things gets clear by checking
HashSet.java from JDK source code. All you need to look at is, how elements are stored in HashSet and how they are retrieved from HashSet. Since HashSet doesn't provide any direct method for retrieving object e.g.
get(Key key) from
HashMap or
get(int index) from List, only way to get object from
HashSet is via Iterator. See
here for
code example of iterating over HashSet in Java. When you create an object of HashSet in Java, it internally create instance of backup Map with default initial capacity 16 and default load factor 0.75 as shown below :
Read full article from How HashSet Internally Works in Java | Java67