Sobes.tech
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:

  1. The hash code of the key is computed using the hash function.
  2. The hash code is converted into an array index (usually by taking the remainder of division by the array size).
  3. The corresponding bucket is searched for an element with a matching key (since collisions can occur, a linked list or tree is used).
  4. 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.

How does HashMap retrieve a value based on a key… - sobes.tech