Sobes.tech
Junior

How is object storage implemented in HashMap?

sobes.tech AI

Answer from AI

Objects are stored as key-value pairs. HashMap uses an array of "buckets". When adding a pair:

  1. The hash code of the key is computed using hashCode().
  2. Using the hash code, the index of the bucket in the array is determined.
  3. The pair Entry (or an equivalent in newer Java versions), containing the key, value, and hash code, is placed into this bucket.
  4. If there are already objects in the bucket, they form a linked list or a tree (in case of many collisions).

When retrieving an object by key:

  1. The hash code of the key is computed.
  2. The index of the bucket is determined.
  3. Inside the bucket, an object with a key for which equals() returns true, and hash codes match, is searched.

Keys should be immutable and have properly implemented hashCode() and equals() methods.