Skip to content

Commit 9986675

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

1 file changed

+1
-2
lines changed

Section 25 Collections Frameworks/Map Interface/HashMap/src/HashMapChainingDemo.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import java.util.LinkedList;
22
import java.util.List;
33

4-
/**
5-
* Simple custom HashMap-like demo to show chaining using LinkedList.
4+
/* Simple custom HashMap-like demo to show chaining using LinkedList.
65
* Uses a very simple hash function (sum of chars % capacity) to force collisions.
76
87
* chaining (LinkedList) inside a custom HashMap so you can see collisions and how entries chain inside a bucket.

0 commit comments

Comments
 (0)