HashSet vs HashMap

Given in simple terms with example codes in respective links. Start reading Differences between HashSet and HashMap.

Both look something same but are very different in each respect. Following tables give you both differences and similarities.

Two programs are given on HashSet and HashMap.

Both belong to Collections framework. One difference of eye-catching is HashSet stores single values and HashMap stores key/value pairs.

HashSet vs HashMap: DIFFERENCES
HashSet HashMap
HashSet implements interface Set HashMap implements interface Map
Stores data single values Stores data in key/value pairs
Adding method is add() Adding method is put()
Duplicate values are not accepted (only unique values) Duplicates keys are not accepted (only unique keys) but allows duplicate values
Preferred to store values like storing all students roll numbers without relevant to marks Preferred to store marks linked to student like student roll number vs marks
Hashcode value evaluated internally on the basis of key Hashcode is evaluated on the basis of value
Synchronized version can be obtained using Collections.synchronizedSet() Synchronized version can be obtained using Collections.synchronizedMap()

HashSet vs HashMap: SIMILARITIES

1. Both belong to the Collections framework.
2. Methods of both are not synchronized and thereby not worthy to be used (not thread- safe) in multithreaded environment.
3. Elements of both are not ordered.
4. HashSet accepts null key and HashMap accepts both null key and null value.

Leave a Comment

Your email address will not be published.