What will happen if you try to store a key that is already present in HashMap?

If you try to store a key that is already present in a HashMap, the existing value associated with that key will be replaced by the new value that you are trying to put. The HashMap in Java does not allow duplicate keys; each key in the map must be unique.

Here's how it works:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> hashMap = new HashMap<>();

        // Put key-value pairs in the HashMap
        hashMap.put("one", 1);
        hashMap.put("two", 2);
        hashMap.put("three", 3);

        // Print the original HashMap
        System.out.println("Original HashMap: " + hashMap);

        // Put a key that is already present
        hashMap.put("two", 22);

        // Print the updated HashMap
        System.out.println("Updated HashMap: " + hashMap);
    }
}

Output:

Original HashMap: {one=1, two=2, three=3}
Updated HashMap: {one=1, two=22, three=3}

As you can see, when we tried to put the key "two" with the value 22, which is already present in the HashMap, it updated the value associated with the key "two" to 22. The previous value 2 was replaced by the new value. 

So, in summary, if you attempt to store a key that is already present in a HashMap, the existing key-value pair will be updated with the new key-value pair, effectively replacing the previous value with the new value.


Comments