Commit ef98ff4
committed
feat(HashMapPractice2): implement simple hash function demo using ASCII sum modulo
What
- Added `simpleHash(String key)` method to compute a basic hash:
- Iterates over each character in the string.
- Sums ASCII values of all characters.
- Returns `sum % 10` as the hash.
- Demonstrated with `"ABC"` and `"CBA"` producing identical hash values.
Why
- To illustrate how custom/simple hash functions work.
- Shows that strings with the same character set in different orders can collide.
- Helps understand why real `HashMap` implementations use more complex hash algorithms.
How
1. `"ABC"` → ASCII: `65 + 66 + 67 = 198` → `198 % 10 = 8`.
2. `"CBA"` → ASCII: `67 + 66 + 65 = 198` → `198 % 10 = 8`.
3. Both map to the same bucket index `8` → **hash collision**.
Key Notes
- This simple hash function is **not good in practice**:
- Different permutations of characters (e.g., `"ABC"`, `"CBA"`, `"BAC"`) will produce the same hash.
- Leads to frequent collisions when used in a hash table.
- Java’s `HashMap` uses a much stronger hash spread function to reduce collisions.
Real-world takeaway
- Always use robust hashing strategies for keys.
- Simple modulo-based hashes are useful only for **teaching/demo** purposes, not production.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 2b04253 commit ef98ff4
File tree
1 file changed
+5
-11
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+5
-11
lines changedLines changed: 5 additions & 11 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | | - | |
9 | | - | |
| 6 | + | |
| 7 | + | |
10 | 8 | | |
11 | | - | |
| 9 | + | |
12 | 10 | | |
13 | 11 | | |
14 | 12 | | |
15 | 13 | | |
16 | 14 | | |
17 | 15 | | |
18 | | - | |
19 | | - | |
20 | | - | |
21 | 16 | | |
22 | | - | |
23 | | - | |
24 | | - | |
| 17 | + | |
| 18 | + | |
0 commit comments