Commit 26708aa
committed
feat(HashMap): add demo showing hash collisions with a simple custom hash function
What
- Added `CollisionInHashMapDemo` class with a `main` method.
- Implemented `simpleHash(String key)` function that:
- Sums ASCII values of characters.
- Returns sum modulo 10 to simulate bucket index in a hash table.
- Demonstrated how two different strings (`"ABC"` and `"CBA"`) can produce the same hash → collision.
Why
- To illustrate the **concept of collisions** in hashing.
- Real-world hash-based structures (HashMap, HashSet) must handle collisions because different keys can map to the same bucket index.
- Helps understand why Java’s `HashMap` uses both `hashCode()` and `equals()` for proper key management.
How
1. `"ABC"`:
- A = 65, B = 66, C = 67
- Sum = 198 → 198 % 10 = 8
2. `"CBA"`:
- C = 67, B = 66, A = 65
- Sum = 198 → 198 % 10 = 8
3. Both yield hash `8` → **collision** occurs (different keys, same bucket index).
4. Program prints these results to show how collisions arise.
Logic Recap
- Hash function reduces a large key space into a small set of bucket indexes.
- Collisions are inevitable because many keys map into fewer buckets.
- Good hashing strategies minimize collisions, but data structures must also resolve them (via chaining or open addressing).
Real-Life Application
- Explains why a robust `hashCode()` implementation is critical for user-defined objects used in HashMap.
- Demonstrates how two different strings can end up in the same bucket.
- Prepares foundation for understanding HashMap internals (buckets, linked lists, tree bins).
Notes
- This demo deliberately uses a weak hash function (`sum % 10`) to force collisions.
- In practice, Java’s `hashCode()` + HashMap’s spreading function reduce collisions but cannot eliminate them.
- Collision handling ensures map integrity (values not lost, proper key lookup).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 0d3306c commit 26708aa
File tree
1 file changed
+42
-0
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+42
-0
lines changedLines changed: 42 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
0 commit comments