HashSet and HashMap design |
What Is HashSet?
HashSet
is one of the data structures in the Java Collections framework.Let’s see the important points:
- It stores
unique
elements and permits null - Do not allows duplicates
- It is backed by a
HashMap
- It doesn’t maintain insertion order
- It is not thread-safe
How HashSet Object Is Created and Initialized?
Whenever we create an instance of HashSet it internally creates an instance of HashMap, basically, each HashSet is backed by a HashMap internally. Let’s see the code block to understand this:
HashSet Object Creation:
HashSet Constructor:
Every
HashSet
object has a map
field of type HashMap
. This reference variable gets initialized when the HashSet() constructor is called at the time of the creation of the HashSet object.Note that
HashMap
stores the entries in key-value pairs but HashSet
is a set of unique elements. Hence the HashSet entries are made key-value pairs using a dummy Object called PRESENT
.Initial capacity ofHashSet
is 16 and the load factor of 0.75.
How the Elements Are Added to HashSet?
The add method adds the specified element to this set if it is not already present in the backup
map
. If this set already contains the element, the method call leaves the set unchanged, and add method returns false
. Otherwise, it returns true when added successfully.How To Remove an Element From HashSet?
The call to
remove(Object o)
removes the specified element from the set if it is present and returns true otherwise returns false.Now Let’s See a Few Other Important Methods of the HashSet Class:
iterator()
returns an iterator over the elements in this set and the element returned are in no particular order.
size()
returns the number of elements present in this set.
isEmpty()
returns true if this set contains no elements.
contains(Object o)
returns true if this set contains the specified element.
clear()
removes all the elements of this set and the set will be empty after this method call.
- Refer to the image below to get a complete idea of how the set and map are constructed.
Post a Comment