As we all know that a Set is a well-defined collection of distinct objects. Each member of a set is called Element of Set. Set contains unique elements.
In Java, Set interface implements classes like HashSet, LinkedHashSet, TreeSet to achieve the uniqueness.
In this post, we will see how HashSet works internally in Java.
HashSet internally uses HashMap to store its object. Whenever we create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements we enter in the HashSet. The elements we add into HashSet is store as Keys of the HashMap and the Values associated to those keys will be constant.
Lets look into the HashSet class -
Here we can see constructor of HashSet class is internally creating HashMap object. There are four public constructors available in HashSet class, all the constructors creates HashMap objects internally.
Whenever we add an element to HashSet using add() method, it actually calls put() method on internally created HashMap object with element we have specified as a Key and constant PRESENT as its Value.
And whenever we remove an element from HashSet using remove() method, it actually call remove() method on internally created HashMap object.
So we can say HashSet maintains its uniqueness internally through HashMap.
In Java, Set interface implements classes like HashSet, LinkedHashSet, TreeSet to achieve the uniqueness.
In this post, we will see how HashSet works internally in Java.
HashSet internally uses HashMap to store its object. Whenever we create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements we enter in the HashSet. The elements we add into HashSet is store as Keys of the HashMap and the Values associated to those keys will be constant.
Lets look into the HashSet class -
Here we can see constructor of HashSet class is internally creating HashMap object. There are four public constructors available in HashSet class, all the constructors creates HashMap objects internally.
Whenever we add an element to HashSet using add() method, it actually calls put() method on internally created HashMap object with element we have specified as a Key and constant PRESENT as its Value.
And whenever we remove an element from HashSet using remove() method, it actually call remove() method on internally created HashMap object.
So we can say HashSet maintains its uniqueness internally through HashMap.
No comments:
Post a Comment