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:
- The hash code of the key is computed using
hashCode(). - Using the hash code, the index of the bucket in the array is determined.
- The pair
Entry(or an equivalent in newer Java versions), containing the key, value, and hash code, is placed into this bucket. - 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:
- The hash code of the key is computed.
- The index of the bucket is determined.
- Inside the bucket, an object with a key for which
equals()returnstrue, and hash codes match, is searched.
Keys should be immutable and have properly implemented hashCode() and equals() methods.