Skip to content

Commit 753294d

Browse files
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

1 file changed

+3
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
package SortedMapDemo.TreeMapDemo;
2-
31
import java.util.Map;
42
import java.util.HashMap;
53

6-
public class HashMapDemo {
7-
public static void main(String[] args)
8-
{
4+
public class HashMapDemo4 {
5+
public static void main(String[] args) {
96
HashMap<Integer, String> HM = new HashMap<>(Map.of(0,"A",1,"B",2,"C",3,"D"));
107

118
HM.put(4, "E");
@@ -14,4 +11,4 @@ public static void main(String[] args)
1411

1512
System.out.println(HM);
1613
}
17-
}
14+
}

0 commit comments

Comments
 (0)