Junior — Middle
How is a new element added to the HashMap data structure?
sobes.tech AI
Answer from AI
In Java, to add a new element to a HashMap data structure, the put(key, value) method is used. This method takes a key and a value, and adds them to the hash table. If the key already exists, the value is updated.
Example:
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3); // adding key "apple" with value 3
map.put("banana", 5); // adding key "banana" with value 5
// if added with an existing key, the value will be updated
map.put("apple", 10); // now the value for "apple" is 10
Internally, HashMap computes the hash code of the key, determines the index in the bucket array, and adds the key-value pair to the corresponding chain or slot.