Commit 9986675
committed
feat(HashMapChainingDemo): implement custom HashMap with chaining demo
What
- Added `HashMapChainingDemo` with an inner `SimpleHashMap` implementation.
- Uses `LinkedList` arrays as buckets to simulate **chaining** for handling collisions.
- Implements basic operations:
- `put(String, Integer)` → insert/update key-value pairs
- `get(String)` → retrieve value by key
- `printBuckets()` → visualize internal bucket structure with chains
- Includes `Entry` class for storing key-value pairs.
- Demonstrates collisions by using a deliberately simple hash function (`sum of chars % capacity`).
Why
- To illustrate **how hash-based collections handle collisions internally**.
- Shows the difference between open addressing vs. chaining.
- Helps developers understand how Java’s `HashMap` internally uses buckets and chains for collision resolution.
How
1. Created an array of `List<Entry>` to serve as buckets.
2. Implemented `simpleHash(String)` that computes `sum(chars) % capacity`.
3. On `put`, if key exists in the bucket → update value, else add new `Entry`.
4. On `get`, linearly search the bucket for matching key.
5. `printBuckets()` displays each bucket index and its chain.
6. In `main()`, inserted colliding keys (`ABC`, `CBA`, `BAC`, `HELLO`, `OLLEH`) to demonstrate chaining.
Logic
- Keys that hash to the same bucket index are stored in a **LinkedList chain**.
- Lookup traverses the chain until the matching key is found.
- Update modifies the existing entry instead of inserting a duplicate.
Real-life applications
- Explains how Java’s `HashMap`, `Hashtable`, and `ConcurrentHashMap` resolve hash collisions.
- Useful in teaching DS/Algo concepts like hashing, collision handling, and chaining.
- Foundation for building custom hash-based caches, symbol tables, or indexing systems.
Notes
- HashMap in Java uses **bucket array + linked list (or tree from Java 8+)** for collisions.
- The demo’s hash function is intentionally weak to cause frequent collisions.
- Demonstrates `null` buckets, updated values, and retrieval from chains.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 26708aa commit 9986675
File tree
1 file changed
+1
-2
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+1
-2
lines changedLines changed: 1 addition & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
5 | | - | |
| 4 | + | |
6 | 5 | | |
7 | 6 | | |
8 | 7 | | |
| |||
0 commit comments