Middle+
Hash was calculated, bucket found, new value inserted. What happens when a new value with the same hash (collision) arrives?
sobes.tech AI
Answer from AI
In Go, when working with a map, a hash collision (different keys having the same hash) is handled using chaining within a bucket.
The algorithm roughly works as follows:
- The hash of the key is computed.
- The bucket (bin) in the array of buckets is determined by the hash.
- Each bucket stores a list of key-value pairs.
- When inserting a new value with the same hash, Go iterates through the elements in the bucket and compares keys using an equality function.
- If the key matches, the value is updated.
- If the key is new, the element is added to the list in the bucket.
Thus, collisions are handled by storing multiple elements in one bucket and sequentially comparing keys.
Example:
m := make(map[string]int)
m["key1"] = 1
m["key2"] = 2 // key2 may have the same hash as key1
// When inserting key2, Go checks the bucket and adds or updates the value