Commit 9bcf1f1
committed
feat(HashTable): add demo showing legacy synchronized Hashtable behavior
What
- Added `HashTable` class to demonstrate basic usage of `java.util.Hashtable`.
- Created a `Hashtable<Integer, String>` and inserted several key–value pairs.
- Printed the hashtable, retrieved a value by key, and tested `containsKey`.
- Attempted to insert a null key and null value to trigger `NullPointerException`.
Why
- To illustrate the differences between `Hashtable`, `HashMap`, and `ConcurrentHashMap`.
- Shows that `Hashtable` is synchronized, does not allow null keys or null values, and is considered a legacy class.
- Demonstrates what happens when null key/value is inserted.
How
- Step 1: Instantiate `Hashtable<Integer, String>`.
- Step 2: Put sample entries: (1 → "Apple"), (2 → "Banana"), (3 → "Cherry").
- Step 3: Print entire table and access by key (`get(2)`).
- Step 4: Use `containsKey(2)` to verify key presence.
- Step 5: Call `hashtable.put(null, "value")` and `hashtable.put(4, null)` to demonstrate null handling (throws `NullPointerException`).
Logic
- Inputs: integer keys and string values.
- Outputs:
- Console log of the hashtable contents.
- Specific value retrieval (`Banana` for key 2).
- Boolean for containsKey check.
- Runtime exception when inserting null key or null value.
- Flow:
1. Insert entries → stored in synchronized hash buckets.
2. Printing uses `toString()`, showing contents in `{}`.
3. Null insertion triggers exception.
Real-life applications
- Rarely used in modern code; kept for backward compatibility.
- Historically used for thread-safe maps before `ConcurrentHashMap`.
- Now mainly educational to show legacy synchronization and null restrictions.
Notes
- Hashtable is synchronized at method level, so slower under contention.
- Does not allow **null keys** or **null values** (unlike HashMap).
- Collision handling uses linked lists (pre-Java 8 style).
- Prefer `HashMap` (unsynchronized) or `ConcurrentHashMap` (concurrent) in new code.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 15a0f7a commit 9bcf1f1
File tree
1 file changed
+6
-11
lines changed- Section 25 Collections Frameworks/Map Interface/Hash Table/src
1 file changed
+6
-11
lines changedLines changed: 6 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 | 6 | | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
15 | 10 | | |
16 | 11 | | |
17 | 12 | | |
| |||
21 | 16 | | |
22 | 17 | | |
23 | 18 | | |
24 | | - | |
25 | | - | |
| 19 | + | |
| 20 | + | |
26 | 21 | | |
27 | | - | |
| 22 | + | |
0 commit comments