What's happening?
- The key is hashed — here, its character codes are added up — and the hash modulo the number of buckets picks the bucket.
- PUT stores the entry in that bucket; GET and REMOVE go straight to the same bucket.
- When two keys land in one bucket (a collision), the bucket keeps a short list and is walked entry by entry.
Complexity
- Time
- O(1) on average for put, get and remove; O(n) in the worst case
- Space
- O(n)
Where you'll meet it
Caches, counting word frequencies, de-duplicating, database indexes in memory, session stores, and the two-sum style of interview problem.
Common mistake
Using a mutable object as a key, or overriding equals() without hashCode() in Java — the map then looks in the wrong bucket and "loses" entries.
FAQ
Why is a HashMap O(1)?
The hash tells it which bucket to look in, so the work does not grow with the number of entries — as long as buckets stay short.
What is a collision?
Two different keys hashing to the same bucket. Chaining keeps both in a small list in that bucket.
What is the load factor?
Entries divided by buckets. Java's HashMap doubles its buckets when it passes 0.75, keeping lists short.
Is this the hash function real HashMaps use?
No — summing character codes is chosen to be easy to follow, and it collides a lot. Real hashes spread keys far more evenly.