Commit 2b04253
committed
feat(HashMapPractice): demonstrate custom load factor, duplicate key handling, conditional remove
What
- Added `HashMapPractice` to explore advanced `HashMap` operations and behaviors:
- Custom capacity and load factor initialization.
- Duplicate key insertion (value replacement).
- Conditional removal using `remove(key, value)`.
- Checking membership with `List.contains()`.
Why
- Helps understand internal HashMap tuning (`initialCapacity`, `loadFactor`).
- Demonstrates how HashMap handles **duplicate keys** (latest value overwrites old one).
- Shows usage of `remove(Object key, Object value)` which only removes if both match.
- Illustrates interoperability with `List.contains()` for simple membership checks.
How
1. Created a `HashMap<Integer, String>` with **initial capacity = 17** and **load factor = 0.5**.
- Load factor `0.5` means rehashing will occur when the table is half full (more frequent resizing).
2. Inserted entries:
- `(31, "Shubham")`
- `(11, "Akshit")`
- `(2, "Neha")`, then `(2, "Mehul")` → key `2` updated, "Neha" replaced with "Mehul".
3. Used `remove(31, "Nitin")`:
- Fails because value did not match (`map` still contains `31=Shubham`).
- Returns `false`.
4. Demonstrated `List.contains(32)` on a fixed list `[2, 4, 32, 43, 4, 432]` → returns `true`.
Key Notes
- **Duplicate keys** overwrite old values, size does not increase.
- `remove(key, value)` = safe way to delete only if mapping matches exactly.
- Load factor tuning is rarely needed; default `0.75f` balances performance & memory.
- `HashMap` iteration order is **unpredictable**.
Real-world usage
- Custom load factor may be used for memory-sensitive or performance-critical scenarios.
- Conditional removal ensures correctness in concurrent or multi-thread contexts.
- Membership checks in lists/maps are common in data filtering pipelines.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 753294d commit 2b04253
File tree
1 file changed
+5
-3
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+5
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
| 5 | + | |
7 | 6 | | |
8 | 7 | | |
9 | 8 | | |
10 | 9 | | |
| 10 | + | |
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
| 14 | + | |
14 | 15 | | |
15 | 16 | | |
16 | 17 | | |
17 | 18 | | |
| 19 | + | |
18 | 20 | | |
19 | 21 | | |
20 | | - | |
| 22 | + | |
0 commit comments