Commit 753294d
committed
feat(HashMapDemo4): add HashMap initialization with Map.of and dynamic updates
What
- Implemented `HashMapDemo4` to demonstrate creating a `HashMap` from an immutable `Map.of()`
and then adding more entries dynamically.
- Prints the final map contents to show that new insertions work alongside the initial values.
Why
- `Map.of()` (Java 9+) creates a compact, immutable map which cannot be modified directly.
- Passing it into the `HashMap` constructor allows creating a **mutable copy** that can be updated.
- This demonstrates a modern and concise way to bootstrap a `HashMap` with initial values.
How
1. Created a `HashMap<Integer, String>` using `new HashMap<>(Map.of(...))` with entries `{0=A, 1=B, 2=C, 3=D}`.
2. Inserted additional entries dynamically using `put`:
- `4 -> E`
- `5 -> F`
- `6 -> G`
3. Printed the map contents, which now includes both initial and newly added values.
Key Notes
- `Map.of(...)` creates an **immutable map**, so you cannot add/remove directly on it.
- Wrapping it with `new HashMap<>(...)` gives you a **mutable copy** that can be extended.
- `HashMap` does **not guarantee order** in output — order may vary depending on hashing.
- For predictable ordering: use `LinkedHashMap` (insertion order) or `TreeMap` (sorted order).
Real-world usage
- Useful for quickly initializing maps with default values/configuration,
then extending them dynamically at runtime.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9dda328 commit 753294d
File tree
1 file changed
+3
-6
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+3
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 4 | + | |
| 5 | + | |
9 | 6 | | |
10 | 7 | | |
11 | 8 | | |
| |||
14 | 11 | | |
15 | 12 | | |
16 | 13 | | |
17 | | - | |
| 14 | + | |
0 commit comments