HashMap Basics
Java HashMaps store key-value pairs. HashMaps can contain null keys and null values, but cannot contain duplicates. HashMap do not store or retrieve elements in the order that the same were added to the HashMap.
Use cases for HashMaps
| HashMaps do not store duplicates, but these can be easily be adapted for use cases where we need to count frequency of duplicate elements that are found in an array or collection.
|
| HashMaps are used for storing configurations as key-value pairs.
|
| HashMaps are used in cache implementations.
|
Advantages of HashMaps
| HashMaps are efficient for constant time access for operations such as get, put, remove.
|
| HashMaps allow adding one null key and multiple keys with null values.
|
| Hashmaps can handle large key value mappings without degrading performance, if the hashing function is properly implemented.
|
| HashMaps are not thread-safe so multiple threads can read /access the same concurrently.
|
Disadvantages of HashMaps
| Keys are not sorted in HashMaps.
|
| HashMaps do not have index based access.
|
| HashMaps underlying data structures (hashtable) consumes more memory.
|
Time Complexity of Java HashMap operations:
Following table shows time complexity metrics for HashMap operations:
| Operation |
Complexity |
| Add operation. |
O(1) |
| Remove/Delete operation. |
O(1) |
| Contains/lookup operation. |
O(1) |
| Get size of HashMap. |
O(1) |