Junior — Middle
Can you explain the internal structure and operation of HashMap in Java?
sobes.tech AI
Answer from AI
HashMap in Java is a data structure for storing key-value pairs with fast access by key.
Internal structure:
- HashMap uses an array of buckets.
- A hash code is computed for the key, which is then transformed into an array index.
- Each bucket stores elements with the same index, usually in the form of a linked list or a tree (since Java 8, if there are many collisions).
Operation:
- When inserting an object, the index is calculated based on the hash of the key.
- If the bucket is empty, the element is placed there.
- If the bucket is occupied, a check is performed to see if the key is equal (equals) to update the value or add a new element.
- When searching by key, the index is also calculated, and then the elements in the bucket are iterated to find a match.
Example:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
int value = map.get("apple"); // 5
Thus, HashMap provides amortized constant time access O(1), but with many collisions, it can degrade to O(n).