Search code examples
hashprogramming-languages

How Do Hashes Work in Programming?


How do hashes work in programming? How I think of a hash is something that allows me the ability to use some unique value to retrieve some data. Like if we have an array and I start to put things in the array, if I have another variable that keeps track of what item is in slot 0,1,2... then I have that instant ability to find an item. Is that hashing?

What is the purpose of a hash?

When should a hash be implemented? What's a hash similar to in terms of data structure?

What I think I know about hashes is that it allows us the ability to retrieve the item within O(1). Is that correct?


Solution

  • A hash map / dictionary is a key/value data structure that stores objects in buckets based on the value of a hash function. These keys must be unique but the hash function values (sometimes called hashcodes) aren't necessarily unique.

    Like if we have an array and I start to put htings in the array, if I have another varible that keeps track of what item is in slot 0,1,2... then I have that instant ability to find an item. Is that hashing?

    No. A hash function is a deterministic function that always gives the same value for an object. The hash code does not change depending on where the object is stored.

    What I think I know about hashes is that it allows us the ability to retrieve the item within O(1). Is that correct?

    Nearly. A dictionary has O(1) complexity for lookups if there are not too many hash code collisions. However if the hash function is poor and every object has the same hash value then a dictionary could have O(n) performance instead.