Commit 741f33e
committed
feat(HashtableComputeDemo): add demo of compute() and computeIfAbsent() in Hashtable
What
- Added `HashtableComputeDemo` to showcase the `compute` and `computeIfAbsent` methods.
- Inserted initial key–value pairs: (1 → "A"), (2 → "B"), (3 → "C").
- Recomputed value at key `2` with `compute()`, appending `"Z"` to `"B"`.
- Added new entry (7 → "Z7") with `computeIfAbsent()`.
Why
- To demonstrate how modern Map API methods work with legacy synchronized `Hashtable`.
- `compute` allows atomic recomputation of a mapping based on its current value.
- `computeIfAbsent` is useful for lazy initialization of missing keys.
How
- Step 1: Populate hashtable with three entries.
- Step 2: Call `ht.compute(2, (k, v) -> v + "Z")`:
- Lambda receives key=2 and value="B".
- Returns "BZ", which replaces old value.
- Step 3: Call `ht.computeIfAbsent(7, k -> "Z"+k)`:
- Since key 7 was absent, computes "Z7" and inserts (7 → "Z7").
- Step 4: Print table before and after recomputations.
Logic
- Inputs: integer keys, string values.
- Outputs:
- Before: `{3=C, 2=B, 1=A}`
- After: `{3=C, 2=BZ, 1=A, 7=Z7}`
- Flow:
1. Initial table with 3 entries.
2. `compute()` modifies existing entry at key 2.
3. `computeIfAbsent()` inserts a new entry for missing key 7.
Real-life applications
- Caching: lazily populate values only when needed.
- Counters or accumulators: recompute value based on existing.
- Thread-safe updates in legacy systems using `Hashtable`.
Notes
- `Hashtable` is synchronized, so these methods are thread-safe but slower than modern alternatives.
- `compute` can overwrite existing mappings.
- `computeIfAbsent` only runs the lambda when key is missing.
- Modern recommendation: prefer `ConcurrentHashMap` or `HashMap` unless legacy compatibility required.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9bcf1f1 commit 741f33e
File tree
1 file changed
+28
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Hash Table/src
1 file changed
+28
-0
lines changedLines changed: 28 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
0 commit comments