Skip to content

Commit ef98ff4

Browse files
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

1 file changed

+5
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
1-
package HashMapDemo;
2-
31
public class HashMapPractice2 {
42
public static void main(String[] args) {
53
System.out.println(simpleHash("ABC"));
64
System.out.println(simpleHash("CBA"));
75
}
8-
public static int simpleHash(String key)
9-
{
6+
7+
public static int simpleHash(String key) {
108
int sum = 0;
11-
for (char c : key.toCharArray()) // Convert string to char array and iterate
9+
for (char c : key.toCharArray()) // Convert string to a char array and iterate
1210
{
1311
sum += (int) c; // Sum ASCII values of characters
1412
}
1513
return sum % 10; // Return sum modulo 10 as the hash
1614
}
1715
}
18-
/*
19-
"ABC" ? ASCII values: A (65) + B (66) + C (67) = 198
20-
198 % 10 = 8
2116

22-
"CBA" ? ASCII values: C (67) + B (66) + A (65) = 198
23-
198 % 10 = 8
24-
*/
17+
// "ABC" ? ASCII values: A (65) + B (66) + C (67) = 198. 198 % 10 = 8
18+
// "CBA" ? ASCII values: C (67) + B (66) + A (65) = 198. 198 % 10 = 8

0 commit comments

Comments
 (0)