Junior — Middle
What are the consequences of inserting an element with a key that already exists in the HashMap?
sobes.tech AI
Answer from AI
If you insert an element with a key that already exists in a Java HashMap, the old value associated with that key will be replaced with the new one. That is, the key remains the same, but the value is updated.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 100);
map.put("key1", 200); // the value for "key1" will be replaced with 200
System.out.println(map.get("key1")); // Will output 200
Thus, HashMap does not store duplicate keys but updates the value for an existing key.