Junior — Middle
What is the internal data structure of the HashMap bucket used for storing elements?
sobes.tech AI
Answer from AI
The internal structure of a HashMap bucket is based on an array of buckets, where each bucket contains either a linked list or a tree (red-black tree) of elements that have the same hash code (collisions).
Initially, all elements with the same hash index are stored in a linked list. If the number of elements in a bucket exceeds a certain threshold (usually 8), the linked list is converted into a red-black tree to improve search performance from O(n) to O(log n).
Each element is stored as a Node object containing the key, value, hash, and a link to the next element in the list or tree node.
Thus, HashMap provides fast access to elements by key, minimizing collisions and optimizing search.