Introduction
Understanding the HashMap
class is essential for developers, both in real-world applications and interviews. In this post, we’ll explore how to insert, update, and manage key-value pairs in a HashMap
. This knowledge will also lay the groundwork for our next article, where we’ll dive into HashSet
and see how the two collections relate.
What is a HashMap?
A HashMap
stores data as key-value pairs, allowing efficient lookups, updates, and deletions. Here are some important characteristics:
- Keys are unique: If a key already exists, the value gets replaced.
- Values can be duplicated: Same values can be mapped to different keys.
-
Average time complexity for operations like
put()
,get()
, andremove()
is O(1).
Let’s explore these behaviors in more detail through code snippets.
1. Inserting Key-Value Pairs Using put()
The put()
method adds a key-value pair to the map. However, if the key already exists, the old value will be replaced.
Map<Integer, Integer> map = new HashMap<>();
// Insert two key-value pairs
map.put(1, 2);
map.put(2, 3);
Explanation:
Here, we insert two entries:
- Key
1
maps to the value2
- Key
2
maps to the value3
Now, what happens if we try to insert a new value with the same key?
2. Handling Duplicate Keys
// Replacing an existing value
map.put(2, 4); // Key 2 already exists, so the value is replaced.
The key 2
already existed with the value 3
, but when we call put(2, 4)
, the new value 4
replaces the old one. This is the default behavior of HashMap
.
Why It Matters
In many situations, you may not want values to be replaced if a key already exists—this can lead to data loss if not handled carefully. In such cases, we can use the putIfAbsent()
method.
3. Preventing Overwrites with putIfAbsent()
// Ensuring value isn't replaced if key exists
map.putIfAbsent(2, 5);
The putIfAbsent()
method only inserts a value if the specified key is not already present in the map. Since key 2
is already associated with the value 4
, the method call here has no effect.
4. Printing the Final Map
System.out.println(map); // Output: {1=2, 2=4}
The output shows that key 2
retains the value 4
because putIfAbsent()
did not overwrite the existing value.
Summary of Key Methods
-
put(K key, V value)
: Inserts or replaces the value for the given key. -
putIfAbsent(K key, V value)
: Inserts the value only if the key is not present.
Conclusion
The HashMap
class is a powerful tool in Java for storing key-value pairs, but it’s crucial to understand its behavior with duplicate keys. Knowing when to use put()
versus putIfAbsent()
can help you avoid data loss and write efficient code. With O(1) average time complexity for basic operations, HashMap
is a go-to choice for many performance-critical tasks.
Stay tuned for the next post, where we’ll explore HashSet
and how it ensures uniqueness using a HashMap
internally!
Related Posts
Happy Coding!