Quick revision
The short answer
A hash function turns a key of any size into a fixed-size integer, its hash code, which a hash table squeezes into a bucket number so it can go straight to one bucket. A good one is deterministic and consistent with equals, spreads keys evenly by using the whole key and mixing small changes, and is fast to compute.
The solution
What it costs
| Property | What it means | What goes wrong without it |
|---|---|---|
| Deterministic | same key, same hash code, every time | a stored key can never be found again |
| Consistent with equals | equal keys have equal hash codes | duplicates in a HashSet, missed lookups |
| Uniform spread | keys spread evenly over buckets | long chains, lookups slow toward O(n) |
| Uses the whole key | every character or field affects the result | keys differing in an ignored part collide |
| Mixes small changes | a one-character change moves the code a lot | similar keys crowd into nearby buckets |
| Fast | cheap to compute, about one step per character | every lookup pays the cost |
What to remember
A hash function is the clerk's rule that turns a key into a number, so a hash table can go straight to one bucket instead of searching. It must be deterministic and give equal keys equal codes, or the table becomes wrong. It should use the whole key, mix small changes and spread keys evenly, or the table becomes slow. When a problem asks whether we have seen something, how often, or which items belong together, a hash table built on such a function is usually the tool.
1What a hash function is, starting from a rack of pigeonholes
Picture the rack of pigeonholes in a school office, one small box for each teacher, numbered 0 to 7. A letter arrives, and the clerk must decide which box it goes into. Suppose the office has a fixed rule, a little calculation done on the name written on the envelope that always produces a box number. The clerk applies the rule, drops the letter in, and later, when a teacher asks for their post, applies the same rule to the name and goes straight to the right box without searching the others.
That rule is a hash function. In plain words, a hash function takes a key, which is the thing we want to store or find, such as a name, a word or an object, and turns it into a number. The key can be of any size, a three-letter word or a whole paragraph, but the number always has the same fixed size. In Java that number is an int, and every object can produce one through its method hashCode. We call the number the key's hash code.
Let us see real numbers. In Java, "cat".hashCode() is 98262, "dog".hashCode() is 99644, and Integer.valueOf(42).hashCode() is simply 42. A hash table, the structure behind HashMap and HashSet, then squeezes the hash code down to a box number. A simple way is the remainder after dividing by the number of boxes. With 8 boxes, 98262 % 8 is 6, so "cat" goes in box 6, and 99644 % 8 is 4, so "dog" goes in box 4. These boxes are usually called buckets.
Each cell is one bucket, numbered above it. A key's bucket is its Java hash code modulo 8.
- cat
- 98262 % 8 = 6
- dog
- 99644 % 8 = 4
- bee
- 97410 % 8 = 2
- hen
- 103185 % 8 = 1
- ant, emu
- 96743 % 8 = 7, 100557 % 8 = 5
1Each key went to bucket
hashCode% 8: hen to 1, bee to 2, dog to 4, emu to 5, cat to 6 and ant to 7. Buckets 0 and 3 are still empty.
Notice the one promise that makes all this work. The rule must give the same number every time for the same key. If "cat" went to box 6 today and box 3 tomorrow, the clerk would never find the letter again. This property is called being deterministic, which simply means the answer depends only on the key and nothing else, not the time, not chance. Everything else we ask of a good hash function is about speed, but this one is about being correct at all.
If hash functions seem mysterious, take heart. The idea is no bigger than the pigeonhole rack. The questions an interviewer asks are all about one thing, how well the rule spreads the letters over the boxes, and each property of a good hash function protects that spread in a different way.
Your turn
Solve it before you read on. Above is one example with the result expected for it. If the question leaves something open, such as an empty input or repeated values, note what you would ask the interviewer. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2Why two keys must sometimes share a bucket
A beginner often hopes for a perfect rule, one that gives every key its own box. Let us see why that cannot happen. There are only 8 boxes. If 9 letters arrive for 9 different teachers, at least one box must receive two of them, whatever the rule is. This plain fact has a name, the pigeonhole principle: when there are more items than holes, some hole holds more than one item.
When two different keys land in the same bucket, we call it a collision. Collisions happen even before the squeezing step. An int has about four billion possible values, but there are endlessly many possible strings, so some different strings must share a hash code. Then they will share a bucket in every table, of every size. So no hash function can avoid collisions altogether. What a good one can do is make them rare and scattered, so that keys spread out as if they had been dropped into buckets at random.
So why do collisions not break the table? Because a bucket can hold more than one key. In Java's HashMap each bucket holds a short chain of entries, a little linked list, and the table compares keys with equals to tell them apart. A collision does not make the table wrong; it only makes that bucket slower, because the table must compare against every key in the chain.
3How a hash table uses the function, step by step
Let us now watch a hash table use the function, step by step, the way HashMap does in principle. We have 8 buckets. To put a key in, we compute its hash code, take it modulo 8 to get the bucket, check the chain in that bucket with equals in case the key is already there, and otherwise add it to the chain. To find a key, we compute the bucket the same way and compare only against the keys in that one chain.
In the picture the top row holds the bucket numbers, and the rows beneath hold each bucket's chain. Watch what happens when owl arrives, because its bucket is already taken, and watch how few comparisons each lookup needs.
The top row is the bucket number. Each column below it is that bucket's chain. A lookup compares only the keys in one column.
- size
- 0
1The table starts empty, with 8 buckets and no keys. Every bucket's chain is empty.
- key
- cat
- hash code
- 98262
- bucket
- 6
- size
- 1
2To put cat, we compute "cat".
hashCode(), which is 98262, and 98262 % 8 = 6, so cat goes into bucket 6.- key
- dog
- hash code
- 99644
- bucket
- 4
- size
- 2
3For dog the code is 99644, and 99644 % 8 = 4, so dog goes into bucket 4. No other bucket is looked at.
- key
- bee
- hash code
- 97410
- bucket
- 2
- size
- 3
4For bee the code is 97410, and 97410 % 8 = 2, so bee goes into bucket 2.
- key
- owl
- hash code
- 110468
- bucket
- 4, a collision
- size
- 4
5For owl, 110468 % 8 = 4, but dog is already there.
owl.equals(dog)is false, so owl joins the chain under dog. That is a collision.- key
- hen
- hash code
- 103185
- bucket
- 1
- size
- 5
6For hen, 103185 % 8 = 1, so hen goes into bucket 1. Four buckets used, one with a chain of two.
- looking for
- owl
- bucket
- 4
- comparisons
- 1
7Looking up owl computes the same bucket, 4, and compares owl with the first key there, dog. They are not equal.
- looking for
- owl
- bucket
- 4
- comparisons
- 2
- result
- found
8The next key in the chain is owl, and
owl.equals(owl)is true, so the lookup succeeds after two comparisons.- looking for
- fox
- bucket
- 7
- comparisons
- 0
- result
- not found
9Looking up fox computes 101583 % 8 = 7. Bucket 7 is empty, so fox is not in the table, and no key was compared at all.
Let us read the picture back. Each put and get did one calculation to choose a bucket, and then compared at most two keys, however many keys the table held. That is where the famous O(1) average cost of a hash table comes from. O(1), read as constant, means the work does not grow as the table grows, as long as the chains stay short.
Now imagine a bad rule that sent all five keys into bucket 4. The table would still be correct, because equals still decides what matches, but every lookup would walk one long chain, and with n keys that is O(n) work, no better than searching a plain list. The hash function does not decide whether the table is right. It decides whether the table is fast.
4The properties of a good hash function, and why each one matters
Now we can ask what makes a hash function good, and each answer will be a way of keeping the chains short or keeping the table correct. The table below lists the properties, each with the failure that shows why it matters. We will then take the important ones slowly.
| Property | What it means | What goes wrong without it |
|---|---|---|
| Deterministic | same key, same hash code, every time | a stored key can never be found again |
| Consistent with equals | equal keys have equal hash codes | duplicates in a HashSet, missed lookups |
| Uniform spread | keys spread evenly over buckets | long chains, lookups slow toward O(n) |
| Uses the whole key | every character or field affects the result | keys differing in an ignored part collide |
| Mixes small changes | a one-character change moves the code a lot | similar keys crowd into nearby buckets |
| Fast | cheap to compute, about one step per character | every lookup pays the cost |
The highlighted row is the one Java programmers most often get wrong, so let us go slowly. Java's rule, stated in the documentation of Object, is that if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Why must it? Think of the lookup path in the picture. The table goes to one bucket chosen by the hash code and calls equals only on the keys there. If two equal objects had different hash codes, the second would be sent to a different bucket, equals would never even be called on the pair, and a HashSet would happily store both.
The rule does not work the other way round. Two unequal keys may share a hash code, as owl and dog shared a bucket. That is only a collision, which costs a little speed and nothing else. So the contract is one-way: equal keys must agree, unequal keys should usually differ.
Uniform spread means each bucket receives about the same number of keys, so with n keys and n buckets each chain holds about one key. Using the whole key protects that spread. Go back to the pigeonholes. If the clerk's rule used only the first letter of the surname, every Sharma, Singh and Smith would pile into one box while the box for X stayed empty. Mixing small changes matters for keys like user1, user2 and user3, which differ in one character, because a rule that moves them only slightly can crowd them into neighbouring buckets.
One more angle appears when the keys come from outside, such as the names of fields in a web request. If an attacker knows the hash function, they can craft thousands of keys with the same hash code and make one chain enormous. This is one reason Java's HashMap turns a very long chain into a balanced tree, so the worst case is about log n comparisons instead of n.
5A weak rule and a strong rule on the same keys
Let us test two rules on real keys rather than trust a table. The first, sumHash, adds up the character codes of a string. It is deterministic and fast, but it ignores the order of the characters. The second, polyHash, uses h = 31 x h + c for each character c, which is exactly the formula String.hashCode uses. Each character is multiplied by a different power of 31, so the position of every character matters.
Before the program, try one by hand. For "cat" the sum is 99 + 97 + 116 = 312, and for "act" it is 97 + 99 + 116, also 312. Same letters, same sum, whatever the order. So under sumHash every rearrangement of the same letters collides, and as we saw, keys with the same hash code collide in every table of every size.
Each cell is the hash code of one key: cat, act, tac, dog and god, in that order. Compared cells share their code with a neighbour.
- keys
- cat act tac dog god
- rule
- add the character codes
- distinct codes
- 2 of 5
1Under
sumHash, cat, act and tac all get 312, and dog and god both get 314. Five keys produce only two codes.- keys
- cat act tac dog god
- rule
- h = 31 * h + c
- distinct codes
- 5 of 5
2Under
polyHash, the same five keys get five different codes, because each character is weighted by its position.
The program below makes the same comparison at a larger scale. It hashes 10,000 keys of the form user0, user1 and so on into 1,024 buckets, and reports how many different hash codes each rule produced and how many keys landed in the fullest bucket.
6Running both rules in Java
Here is the program. sumHash and polyHash are the two rules, spread counts codes and the fullest bucket, and main ends with a record used as a key, to show the equals and hashCode contract working.
Let us read the results in the order they print. The first line shows the collision we worked out by hand, 312 and 312. The second shows polyHash giving cat and act different codes, and the third confirms that polyHash is the same calculation as Java's own String.hashCode.
The fourth line is the striking one. The 10,000 user keys produce only 91 different sums, because their character codes add up to numbers in a narrow range, and the fullest bucket holds 615 keys. A lookup there would compare against hundreds of entries. Under polyHash every key gets its own code and the fullest bucket holds 34 keys, against an average of about 10. The last line shows a record, whose generated hashCode agrees with its generated equals, so a new Point(2, 3) is found in the set.
Why 31 in particular? It is an odd number, so multiplying by it never throws information away when the int overflows and wraps around, and it is small enough that 31 x h can be computed quickly as (h << 5) - h, a shift and a subtraction. Nothing else is magic about it.
7How Java builds hash codes for our own classes
For our own classes the rule is simple. Whatever fields equals compares, hashCode should combine, and nothing else. The usual recipe keeps a running result and, for each field, multiplies the result by 31 and adds that field's hash code, the same shape as polyHash. Objects.hash(x, y) does this for us, and a record generates its own hashCode of the same kind from its fields. Leaving a field out is legal but weakens the spread. Including a field that equals ignores breaks the contract, because two equal objects could then differ in that field and get different codes.
HashMap adds one step of its own on top of hashCode. Its bucket array always has a length that is a power of two, such as 16 or 1,024, so it picks a bucket by keeping only the lowest bits of the hash code, which is faster than a division. But then two hash codes that differ only in their high bits would always share a bucket. So HashMap first mixes the high bits into the low ones with h ^ (h >>> 16), a small spreading step that makes a merely decent hashCode good enough in practice.
A beginner sometimes asks whether it is safe to use a mutable object, one whose fields can change, as a key. Let us think it through with the pigeonholes. We store the key in the bucket its hash code chose. Then a field changes, so the hash code changes. When we look the key up, the new code sends us to a different bucket, and the entry seems to vanish, although it still sits in its old bucket using memory. That is why strings, boxed numbers and records with unchanging fields make the best keys.
8How to recognise problems that need hashing
In coding problems we rarely write a hash function ourselves. We use one every time we reach for HashMap or HashSet. The clues that call for hashing are phrases such as have we seen this before, count how often, find the pair that adds up to, group the items that share something, or remove duplicates. Each of them needs a quick way to go from a value to a record about it, and a hash table gives that in O(1) on average, like the clerk going straight to one pigeonhole.
Sometimes the key we hash is built from the data. To group anagrams, for example, we use each word's sorted letters as the key, so cat, act and tac all map to "act". Then the hash function of that built key does the grouping for us. Notice the twist: here we want certain different words to land together, so we choose the key on purpose to make them equal.
Writing a hash function by hand comes up in two places. One is a custom key class, where we must override equals and hashCode together or use a record. The other is a rolling hash, as in the Rabin-Karp substring search, where the polynomial formula from our demonstration is updated in constant time as a window slides along a string, by removing the contribution of the character that leaves and adding the one that enters.
9Follow-up questions
Why must hashCode be overridden whenever equals is overridden?
Object's default hashCode is based on the object's identity, so two separate objects get different codes even when our own equals calls them equal. A HashMap would then look for the second object in a different bucket from the first and never call equals at all, so lookups fail and sets keep duplicates. Overriding both together, using the same fields, keeps equal objects in the same bucket, which is all the contract asks.
What is the difference between a hash function for a table and a cryptographic hash?
A hash function for a table aims for speed and an even spread, nothing more. A cryptographic hash such as SHA-256 must also make it practically impossible to find two inputs with the same output on purpose, or to work backwards from the output to the input. That makes it much slower. Using SHA-256 inside a HashMap would waste time, and using String.hashCode to protect passwords would be insecure, because collisions for it are easy to construct.
If collisions are unavoidable, what keeps a hash table fast as it grows?
The table grows its bucket array. HashMap keeps the average chain short by resizing, roughly doubling the number of buckets, once the number of keys passes three quarters of the number of buckets, called the load factor of 0.75. Every key is then placed again into the larger array. A single resize costs O(n), but it happens rarely enough that the average cost of a put stays O(1). This only helps when the keys have different hash codes, which is why the spread of the function matters so much.
10Conclusion
A hash function is the clerk's rule that turns a key into a number, so a hash table can go straight to one bucket instead of searching. It must be deterministic and give equal keys equal codes, or the table becomes wrong. It should use the whole key, mix small changes and spread keys evenly, or the table becomes slow. When a problem asks whether we have seen something, how often, or which items belong together, a hash table built on such a function is usually the tool.
Open with
A hash function maps a key of any size to a fixed-size integer, its hash code. A hash table reduces that code to a bucket index, goes straight to that bucket, and compares only the keys there with equals.
Then, if they want more
Because there are more possible keys than codes, collisions are unavoidable, so a good function makes them rare and evenly scattered. The properties I look for are these. It must be deterministic, and it must be consistent with equals: equal objects must have equal hash codes, otherwise a HashMap searches the wrong bucket and a HashSet keeps duplicates.
Unequal objects may share a code, which only costs speed. Beyond correctness it should spread keys uniformly, use every part of the key, change a lot when the key changes a little, and be cheap to compute. Adding character codes is a weak example, since all anagrams collide.
Java's String.hashCode uses h = 31 times h plus c, so every position matters. For my own classes I combine exactly the fields equals uses, with Objects.hash or a record, and I keep key fields immutable.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
- Official documentation
- HashSet (Java 21), Arrays (Java 21), ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What is a hash function and what makes a good one?": https://scrivio-interview-library.netlify.app/data-structures/solutions/what-is-a-hash-function-and-what-makes-a-good-one-72cf22/