In this article, we will discuss difference between HashMap and HashSet classes in detail i.e.; HashMap v/s HashSet
1. HashMap v/s HashSet:
HashMap | HashSet |
HashMap implements Map interface | HashSet implements Set interface |
Used to store key-value pairs using put method
Example: hm.put(key, value); | Used to store only unique objects using add method
Example: hs.add(object); |
HashMap doesn’t allow duplicate keys but values can be duplicated | HashSet doesn’t allow duplicate objects |
HashMap allows maximum of one null key but any number of NULL values allowed | HashSet allows maximum of one null object to be added |
HashMap internally uses an array of Entry<K,V> objects | HashSet internally uses HashMap to store unique objects |
Performance-wise, HashMap is faster than HashSet | Performance-wise, HashSet is slower than HashMap |
Q) When to use HashMap ?
- HashMap stores key-value pairs which uses hashing technique to store key-value pairs where methods are NOT synchronized
- So, search operation is faster with multiple threads access
- So, if business requirement is to store key-value pairs for faster search operation or more number of search operation on the basis of keys; without concerning concurrent access of map
- Then, HashMap is the very apt choice
Q) When to use HashSet ?
- HashSet stores unique elements using hashing technique
- So, search operation is faster
- So, if business requirement is to store unique elements for faster search operation or more number of search operation without concerning insertion order
- Then, HashSet is the very apt choice
Related Articles:
- Map interface
- Entry interface
- HashMap class
- LinkedHashMap class
- IdentityHashMap class
- WeakHashMap class
- SortedMap interface
- NavigableMap interface
- TreeMap class
- Hashtable class
- HashMap vs LinkedHashMap
- HashMap v/s LinkedHashMap v/s TreeMap
- HashMap v/s HashSet
- HashMap v/s Hashtable
- Properties class
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
Happy Coding !!
Happy Learning !!