Junior — Middle
What happens in a HashMap if you insert a key-value pair with a key that already exists in the map?
sobes.tech AI
Answer from AI
If you insert a key-value pair into a HashMap with a key that already exists, the old value associated with that key will be replaced with the new value. The size of the map will not change, as the number of unique keys remains the same.
Example in Java:
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