Skip to content

Commit 2b04253

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

1 file changed

+5
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
1-
package HashMapDemo;
2-
31
import java.util.*;
42
public class HashMapPractice {
53
public static void main(String[] args) {
64
HashMap<Integer, String> map = new HashMap<>(17,0.5f);
5+
76
map.put(31, "Shubham");
87
map.put(11, "Akshit");
98
map.put(2, "Neha");
109
map.put(2, "Mehul");
10+
1111
System.out.println(map);
1212

1313
boolean res = map.remove(31, "Nitin");
14+
1415
System.out.println("REMOVED ? :" + res);
1516
System.out.println(map);
1617

1718
List<Integer> list = Arrays.asList(2, 4, 32, 43, 4, 432);
19+
1820
System.out.println(list.contains(32));
1921
}
20-
}
22+
}

0 commit comments

Comments
 (0)