Junior — Middle
How does HashMap retrieve a value based on a key?
sobes.tech AI
Answer from AI
HashMap retrieves a value by key using a hash function, which transforms the key into an array index (bucket) where the value is stored.
Retrieval process:
- The hash code of the key is computed using the hash function.
- The hash code is converted into an array index (usually by taking the remainder of division by the array size).
- The corresponding bucket is searched for an element with a matching key (since collisions can occur, a linked list or tree is used).
- If the key is found, the associated value is returned.
Example in Java:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
Integer value = map.get("apple"); // Hash is computed, bucket is searched, 5 is returned
Thus, HashMap provides quick access to data — on average in O(1) time, if the hash function distributes keys evenly.