Difference between HashMap and HashSet in Java

In this quick article, we will see the difference between HashMap and HashSet which are very popular classes of the Java Collections Framework.

 

1. Implemented Interface

A HashSet is an implementation of Set interface whereas a HashMap is an implementation of Map interface.

 

2. Definition

Both HashSet and HashMap follows contract of their respective interfaces. A HashSet class represents a unique set of elements whereas a HashMap class represents mapping of key to values.

 

3. Implementation Details

HashMap is implemented using a hash table whereas a HashSet is backed by a hash table which is nothing but a HashMap instance.

 

4. Duplicates

HashSet allows only distinct elements, whereas a HashMap doesn’t permit duplicate keys but allows duplicate values.

 

5. Null values

HashSet contains at most one null element whereas a HashMap typically allows null as a key and value except some implementations.

 

When to use HashSet and HashMap?

HashSet can be used when we need to maintain a collection with no duplicates and HashMap when data is key-value pairs and need fast retrieval of value based on some key.

 
References: HashSet and HashMap Javadoc

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of