Inside, a hash map is surprisingly simple: an ordinary array of slots called buckets, plus a hash function that turns any key into a bucket number. Everything else — collisions, resizing — exists to keep that idea fast.
A hash function takes a key and returns a number, and the map takes that number modulo the number of buckets to get an index. The same key always gives the same number, so get lands in the very bucket put used. Strings are hashed by mixing their character codes — Java, for example, computes h = h * 31 + code for each character.
Members only · free account
The rest of this lesson, with 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson