Junior — Middle
Can you explain the internal structure and working mechanism of a hash table in Java?
sobes.tech AI
Answer from AI
The hash table in Java (e.g., HashMap) is a data structure that stores key-value pairs and provides fast access based on the key.
Internal structure:
- It is based on an array of buckets.
- Each bucket contains either
nullor a linked list (or tree if many elements) of entries with the same hash code modulo the array size.
How it works:
- When adding an element, its hash code is computed, and the index in the array is determined.
- If the bucket is empty, the element is placed there.
- If the bucket is occupied, a search is performed in the linked list (or tree) for a matching key:
- If found, the value is updated.
- If not, the element is added to the list.
- When the load factor exceeds a threshold, the array is resized (rehash) to maintain performance.
This approach provides average operation complexities close to O(1) for insert, search, and delete.
Example usage:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 100);
Integer value = map.get("key1"); // fast retrieval by key