Commit 9c36860
committed
feat(ImmutableMapDemo): demonstrate creating immutable maps in Java
What
- Added ImmutableMapDemo class.
- Showed 4 approaches:
1. Normal mutable HashMap (map1).
2. Immutable view using Collections.unmodifiableMap() (map2).
3. Immutable map using Map.of() (map3).
4. Immutable map using Map.ofEntries() (map4).
- Printed behavior before and after modification attempts.
Why
- To teach the differences between mutable maps, immutable views, and truly immutable maps in Java.
- Highlights caveats of unmodifiableMap (changes in original reflect in the view).
- Introduces Java 9+ factory methods Map.of and Map.ofEntries as safer alternatives.
How
- map1: created mutable HashMap and inserted entries.
- map2: wrapped map1 with Collections.unmodifiableMap().
- map3: used Map.of() for up to 10 entries.
- map4: used Map.ofEntries() for arbitrary entries.
- Demonstrated that modifying map1 reflects in map2, while map3 and map4 reject modifications with UnsupportedOperationException.
Logic
- Inputs:
- Key-value pairs like ("A",1), ("B",2), ("Shubham",98).
- Processing:
- Map1 accepts updates directly.
- Map2 proxies to map1 for reads but blocks direct writes.
- Map3 and map4 are created as fixed-size immutable maps.
- Outputs:
- map1 → reflects all additions.
- map2 → mirrors changes in map1 but cannot be modified directly.
- map3 → fixed {Shubham=98, Vivek=89}.
- map4 → fixed {Akshit=99, Vivek=99, Neha=95}.
Real-life applications
- Collections.unmodifiableMap → when you need to share a read-only view of a mutable map.
- Map.of / Map.ofEntries → when you want fully immutable maps for constants, config data, or safe multi-threaded access.
- Immutable collections improve safety by preventing accidental modifications and simplify reasoning in concurrent programs.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent f418078 commit 9c36860
File tree
1 file changed
+57
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Immutable Map/src
1 file changed
+57
-0
lines changedLines changed: 57 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 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
0 commit comments