Junior — Middle
What consequences can be expected when trying to insert two identical keys into a HashMap?
sobes.tech AI
Answer from AI
When attempting to insert two identical keys into a HashMap, the second call to put will overwrite the value associated with that key with the new value. As a result, the map will only contain one entry with that key, and the old value will be replaced. The put method returns the previous value if the key already existed, or null if the key was new.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
Integer oldValue = map.put("key", 2); // oldValue will be 1
System.out.println(map.get("key")); // Will print 2
Thus, HashMap does not allow duplicate keys, and new values simply replace old ones.