Difference between HashMap and HashSet

Share


T
his is one of the most famous questions which interviewers consider in an interview. Before we actually see the differences, let me give you a brief description of both.

HashMap is the implementation of Map Interface, which maps a key to value. Duplicate keys are not allowed in a map.  The Following table summaries the characteristics of HashMap.

HashMap

It allows null for both key and value.

It provides better performance. Operations such as adding, removing, or finding an entry based on a key are constant time, as these hash the key.

It is not synchronized ( so, this is not thread-safe).

HashSet is the implementation of Set Interface, which does not allow duplicate value. The Following table summaries the characteristics of HashSet.

HashSet

It does not allow null value.

It is not synchronized ( so, this is not thread-safe).

HashMap Vs HashSet

HashSet is implementation of Set interfaceHashMap Vs HashSet
HashMap is the implementation of Map interface.

HashSet Store only value.
HashMap Stores data in form of key value pair.

HashSet does not allow duplicate values/objects
HashMap allows duplicate value/objects but would not allow duplicate key.

HashSet is slower than hashmap.
HashMap is faster than hashset because the values are associated to unique key

In HashSet, member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.
In HashMap, hashcode value is calculated using key object.