Inside a Dictionary: buckets and collisions
A dictionary turns the key into a number, uses that number to choose a bucket, and only searches inside that one bucket.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Hashing jumps straight to one bucket instead of scanning everything. Two keys that land in the same bucket are a collision, and they are kept in a short chain that is searched one by one.
Code
var map = new Dictionary<int, string>();
map[key] = value;
// What the indexer does inside:
// int hash = key.GetHashCode();
// int bucket = hash % buckets.Length;
// walk the entries in that bucket:
// same key found -> replace the value, otherwise add a new entrystatic void put(int key, String value) {
Map<Integer, String> map = new HashMap<>();
map.put(key, value);
// What put does inside:
// int hash = h ^ (h >>> 16), where h = key.hashCode();
// int bucket = (table.length - 1) & hash;
// walk the entries in that bucket:
// same key found -> replace the value, otherwise add a new entry
}void put(int key, const string& value) {
unordered_map<int, string> map;
map[key] = value;
// What operator[] does inside:
// size_t hash = std::hash<int>{}(key);
// size_t bucket = hash % bucket_count();
// walk the nodes in that bucket:
// same key found -> return that value, otherwise insert a new node
}table = {}
table[key] = value
# What dict does inside (CPython):
# h = hash(key)
# slot = h & (len(slots) - 1)
# probe from that slot:
# same key found -> replace the value, otherwise use the first free slotTips
- This picture uses 5 buckets and never resizes. The real Dictionary uses a prime number of buckets and grows when it fills up, which keeps chains short.
- If many keys share a bucket, lookups slow down towards O(n). A good GetHashCode spreads keys evenly.
In the .NET library
If you override Equals on a key type you must override GetHashCode too, and equal objects must return the same hash. record types do both for you.