346
Difference between HashSet and HashMap class in Java
The HashMap and HashSet in Java are the most popular Collection classes. Both are used for the data structure. The following table describes the difference between HashMap and HashSet:
Basis | HashMap | HashSet |
---|---|---|
Definition | Java HashMap is a hash table based implementation of Map interface. | HashSet is a Set. It creates a collection that uses a hash table for storage. |
Implementation | HashMap implements Map, Cloneable, and Serializable interface es. | HashSet implements Set, Cloneable, Serializable, Iterable and Collection interfaces. |
Stores | In HashMap we store a key-value pair. It maintains the mapping of key and value. | In HashSet, we store objects. |
Duplicate values | It does not allow duplicate keys, but duplicate values are allowed. | It does not allow duplicate values. |
Null values | It can contain a single null key and multiple null values. | It can contain a single null value. |
Method of insertion | HashMap uses the put() method to add the elements in the HashMap. | HashSet uses the add() method to add elements in the HashSet. |
Performance | HashMap is faster/ than HashSet because values are associated with a unique key. | HashSet is slower than HashMap because the member object is used for calculating hashcode value, which can be same for two objects. |
The Number of objects | Only one object is created during the add operation. | There are two objects created during put operation, one for key and one for value. |
Storing Mechanism | HashMap internally uses hashing to store objects. | HashSet internally uses a HashMap object to store objects. |
Uses | Always prefer when we do not maintain the uniqueness. | It is used when we need to maintain the uniqueness of data. |
Example | {a->4, b->9, c->5} Where a, b, c are keys and 4, 9, 5 are values associated with key. | {6, 43, 2, 90, 4} It denotes a set. |
Let’s understand the differences through programs.
Example of HashMap
In the following example, when we add a duplicate element with the same key and different value, then the previous value of the key is replaced by the new value.
When we add a duplicate element with the same key and same value, then the key-value pair does not store second time.
Output:
Example of HashSet
In the following example, we can see that the duplicate values does not store in the HashSet and the null value stores only once.
Output:
Next TopicJava Tutorial