Junior — Middle
How is data stored in a HashMap structure?
sobes.tech AI
Answer from AI
HashMap in Java stores data as key-value pairs using an array of buckets. The key is hashed using the hashCode() method to determine the index of the bucket where the pair will be stored.
If multiple keys hash to the same bucket (collision), the data within the bucket is stored in a linked list or a balanced tree (since Java 8) to speed up search.
When adding an element:
- The hash of the key is computed.
- The bucket index is determined by the hash.
- If the bucket is empty, a new entry is created.
- If the bucket is occupied, a search is performed in the list/tree to update or add a new entry.
This provides quick access to values by key with an amortized complexity of O(1).