Skip to content

Commit 5e61cb4

Browse files
committed
Additional Important Methods and Interview Insights — HashMap + HashTable
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 35e353e commit 5e61cb4

File tree

1 file changed

+125
-0
lines changed

1 file changed

+125
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
Additional Important Methods and Interview Insights — HashMap
2+
3+
4+
Functional-Style Updates (Java 8+)
5+
----------------------------------
6+
- compute(K key, BiFunction remappingFunction):
7+
Updates the mapping for the given key using its current value (or null if absent).
8+
If the function returns null, the key is removed.
9+
10+
- computeIfAbsent(K key, Function mappingFunction):
11+
Inserts a mapping only if the key is absent or mapped to null. Useful for lazy initialization.
12+
13+
- computeIfPresent(K key, BiFunction remappingFunction):
14+
Updates the mapping only if the key already has a non-null value.
15+
16+
- merge(K key, V value, BiFunction remappingFunction):
17+
Combines an existing value with a new one. If the key is absent, it inserts the value;
18+
if present, it computes a new value.
19+
Example use case: counting word occurrences or combining sums.
20+
21+
---
22+
23+
Bulk and Conditional Operations
24+
-------------------------------
25+
- replace(K key, V value): Replace the value for a key.
26+
- replace(K key, V oldValue, V newValue): Replace the value only if the current value matches an expected value.
27+
- replaceAll(BiFunction function): Apply a transformation function to every mapping.
28+
- forEach(BiConsumer action): Iterate through each entry (key, value) to perform an action.
29+
30+
---
31+
32+
Clone
33+
-----
34+
- clone(): Creates a shallow copy of the HashMap.
35+
Keys and values themselves are not deep-copied.
36+
Important to distinguish between shallow vs. deep copies in interviews.
37+
38+
---
39+
40+
Thread Safety and Concurrency
41+
-----------------------------
42+
- Non-synchronized nature: HashMap is not thread-safe. Concurrent modifications without synchronization
43+
cause undefined behavior.
44+
- Alternatives: Use `ConcurrentHashMap` or wrap HashMap with `Collections.synchronizedMap`.
45+
46+
Fail-Fast Iterators:
47+
- Iterators for keySet(), entrySet(), values() are fail-fast.
48+
- If the map is modified structurally during iteration (except via iterator’s remove),
49+
a ConcurrentModificationException is thrown.
50+
- Purpose: Helps detect concurrent modification bugs early — not to provide thread safety.
51+
52+
---
53+
54+
Hash Function and Collision Handling
55+
------------------------------------
56+
- Importance of a good hashCode(): A well-distributed hash reduces collisions.
57+
- Collision resolution:
58+
- Pre-Java 8: Collisions in a bucket were handled via a linked list.
59+
- Java 8+: If collisions in a bucket exceed a threshold, it is transformed into a balanced tree (TreeNode),
60+
reducing worst-case lookup from O(n) to O(log n).
61+
62+
---
63+
64+
Capacity, Load Factor, and Rehashing
65+
------------------------------------
66+
- Initial capacity: Default is 16 buckets.
67+
- Load factor: Default is 0.75, balancing time efficiency and memory usage.
68+
- Rehashing: Happens when size > capacity × load factor. A new, larger table is created and entries are re-distributed.
69+
- Trade-offs:
70+
- Too high capacity → wasted memory.
71+
- Too low load factor → more frequent rehashing, performance penalty.
72+
73+
---
74+
75+
Null Keys and Values
76+
--------------------
77+
- Null key: HashMap allows one null key.
78+
- Null values: Multiple null values are permitted.
79+
- Comparison: Hashtable does not allow null keys or values; TreeMap does not allow null keys.
80+
81+
---
82+
83+
Memory Considerations
84+
---------------------
85+
- Each bucket is an entry node (key, value, hash, next/tree link).
86+
- Large initial capacity may waste memory.
87+
- Poor sizing leads to frequent rehashing, impacting performance.
88+
89+
---
90+
91+
Final Interview Preparation Tips
92+
--------------------------------
93+
- Practical Use Cases:
94+
Choose HashMap when fast lookups are needed, and ordering is not important.
95+
96+
- Code Examples:
97+
Practice using advanced methods like computeIfAbsent (e.g., caching, memoization).
98+
99+
- Conceptual Questions:
100+
- How hashCode affects bucket placement.
101+
- What happens during rehashing.
102+
- Why Java 8 introduced tree bins.
103+
104+
- Comparative Analysis:
105+
- HashMap: fast, unordered, single-threaded.
106+
- TreeMap: ordered by keys (logarithmic operations).
107+
- ConcurrentHashMap: thread-safe, high concurrency.
108+
109+
110+
111+
Feature | HashMap | Hashtable
112+
-----------------------|-------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------
113+
Hierarchy | Part of Java Collections Framework (implements Map, Cloneable, Serializable) | Legacy class (Java 1.0), later retrofitted to implement Map
114+
Thread Safety | Not synchronized (must wrap with Collections.synchronizedMap or use ConcurrentHashMap) | Synchronized by default (thread-safe, but slower in single-threaded scenarios)
115+
Performance | Faster (no synchronization overhead). Average O(1) for put(), get(), remove() | Slower due to synchronized methods. Still average O(1) but less efficient
116+
Null Keys & Values | Allows **one null key** and **multiple null values** | Does **not allow null key** and **null values** at all
117+
Fail-Fast Behavior | Iterators are fail-fast (throw ConcurrentModificationException if structure changes during iteration) | Enumerators are not fail-fast (legacy); Iterators exist but behave differently
118+
Ordering | No ordering of keys or values (unordered) | No ordering of keys or values (unordered)
119+
Iteration Type | Uses **Iterator** (modern, supports fail-fast) | Uses **Enumerator** (legacy, not fail-fast) and Iterator
120+
Use in Modern Code | Preferred in almost all scenarios; thread-safe alternative is ConcurrentHashMap | Considered obsolete/legacy; very rarely used in new code
121+
Introduced | Java 1.2 (part of Collections Framework redesign) | Java 1.0 (before Collections Framework)
122+
Capacity & Load Factor | Default capacity 16, load factor 0.75 (rehashing when exceeded) | Similar, but older implementation details (not as optimized as HashMap)
123+
Concurrent Alternative | Use ConcurrentHashMap for high-performance multi-threaded environments | Use is discouraged; replaced by modern alternatives
124+
Clone Behavior | clone() creates a shallow copy of HashMap | clone() creates a shallow copy of Hashtable
125+
Legacy Compatibility | Fully modern, integrates well with Java Collections utilities | Exists mainly for backward compatibility with old Java code

0 commit comments

Comments
 (0)