Menu

A hash map is just an array that computes its own index
πŸ“°

A hash map is just an array that computes its own index

DEV Community: javaΒ·VLADΒ·3 days ago
#DAy2NiyM
#devtojava#devto#dev#hash#keys
Reading 0:00
15s threshold

A map with a million keys answers a lookup just as fast as a map with ten. No loop. No searching. Your program jumps straight to the answer.

That's not magic, and it isn't a tree. It's one very old trick, plus two failure modes that most people never hear about.

Prefer to watch? Full walkthrough with the bucket animation:

Arrays are the fast part

Start with the one thing computers are genuinely fast at: an array . Ask for item number five and nothing is searched. The machine multiplies the index by the element size, adds it to the start address, and lands on the exact spot in memory. Item five and item five million cost the same.

The catch is that arrays only take positions . You don't think in positions β€” you want the value stored under "email" , or under a user ID, or under a whole string of text.

So the real question is: how do you turn a key like "email" into a position?

The hash function

A hash function takes anything β€” a word, a sentence, an object β€” and gives back a number.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.