Junior — Middle
How do you implement adding a new element to a HashMap data structure?
sobes.tech AI
Answer from AI
In Java, to add a new element to a HashMap, the method put(key, value) is used. If the key already exists, the value is updated; otherwise, a new key-value pair is created. Inside the HashMap, the key is hashed to determine the index in the bucket array, and the element is added to the corresponding bucket.
Example:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3); // adding the key "apple" with value 3
map.put("banana", 5); // adding the key "banana" with value 5
If the key already exists when adding, the value will be updated:
map.put("apple", 10); // now the value for "apple" will be 10