Senior Java interviews often use collection behavior to test whether you understand contracts rather than memorized method names. The difficult bugs usually appear when equality, ordering, mutation, resizing, or concurrency interacts with an otherwise simple-looking map operation.
This article explains how HashMap, ConcurrentHashMap, and TreeMap behave internally, along with the guarantees and limitations of their iterators. It also shows how custom keys, collision handling, atomic update methods, range views, and hot counters affect production designs.
All 20 answers below are free. Want the full set, every answer with a worked example?
Core Java Interview Q&A with working code (200 Qs: OOP internals, concurrency, JVM, streams, JDK 8 to 25)
Get the guideTreat a HashMap key as immutable for as long as it is in the map. If a field used by equals or hashCode changes, remove the entry before changing it and reinsert it afterward, or preferably design the key so that such mutation is impossible.
A lookup computes the key's current hash, spreads it, and selects a bucket. The map does not notice that an existing entry was originally placed using a different hash. Even if the new bucket happens to be the same, the changed equality fields can prevent the key from matching the stored key. The entry is still physically present, so this is a reachability bug rather than data loss.
final class UserKey {
private final long tenantId;
private final String username;
UserKey(long tenantId, String username) {
this.tenantId = tenantId;
this.username = Objects.requireNonNull(username);
}
@Override public boolean equals(Object o) { /* compare both fields */ }
@Override public int hashCode() { return Objects.hash(tenantId, username); }
}
A practical diagnosis and fix are:
remove(oldKey), mutate outside the map, then put(newKey). Ensure the old key instance and state are still usable for removal.In production, correlate misses with updates to entity objects and inspect retained map entries or a heap dump; logging every hash operation is usually too expensive. Immutable keys may require creating a new object for each changed identity, but that cost is safer than silent misses. A record helps with final components, but its component values must themselves have stable equality and hash behavior.
Interview takeaway: A key's equality identity must not change while it is stored; model changes as a new key or remove and reinsert.
equals defines which fields make two keys the same, and hashCode must be derived from that same logical identity. Those identity fields must remain stable while the key is in the map; otherwise the map can both misplace the entry and disagree about whether it matches.
The required contract is one-way but strict: whenever a.equals(b) is true, a.hashCode() must equal b.hashCode(). If equals compares tenantId and username but hashCode uses only username, correctness is preserved, although collisions increase. If equals compares both but hashCode includes a mutable status field, two equal keys can have different hashes, violating the contract. Using the same immutable identity fields avoids both errors and makes the intent reviewable.
final class AccountKey {
private final long tenantId;
private final String accountId;
@Override public boolean equals(Object obj) {
if (!(obj instanceof AccountKey other)) return false;
return tenantId == other.tenantId
&& accountId.equals(other.accountId);
}
@Override public int hashCode() {
return 31 * Long.hashCode(tenantId) + accountId.hashCode();
}
}
Common production symptoms include:
get or containsKey miss despite an entry appearing to exist.HashSet containing what appear to be duplicate values, or a failed remove.Review a custom key by:
A stronger hash function improves distribution but cannot repair an inconsistent equals. Conversely, omitting fields from hashCode is legal only when equals still implies equal hashes; it usually trades performance for simplicity.
Interview takeaway: Define equality once around stable identity fields, and compute the hash from that same identity so the collection contract remains true.
A HashMap resize can put a noticeable latency spike on the thread performing the insertion because it allocates a larger table and redistributes every existing entry. Plan the initial capacity from the expected entry count and load factor so normal growth does not occur on a latency-sensitive path.
The default load factor is 0.75. When the size reaches the threshold, the table generally doubles; the resize work is proportional to the current table and entries, not just the triggering put. Modern Java implementations can split each bin efficiently during transfer, but that still consumes CPU, touches a large amount of memory, and may cause allocation and cache pressure. HashMap is not thread-safe, so this is not a coordinated pause for all users; it is work done by the mutating thread, with unsafe concurrent access being a separate problem.
int expectedEntries = 100_000;
float loadFactor = 0.75f;
int initialCapacity = (int) Math.ceil(expectedEntries / loadFactor);
Map<Key, Value> map = new HashMap<>(initialCapacity, loadFactor);
Capacity planning should:
ceil(expectedEntries / loadFactor) as the conceptual minimum; HashMap rounds the table to an implementation-appropriate power of two.Use JFR, allocation profiling, CPU samples, and latency correlation to identify a resize: look for a large HashMap table allocation and transfer work around the outlier. If shared concurrent mutation is required, use an appropriate concurrent design rather than trying to hide an unsafe resize.
Interview takeaway: Size a HashMap for peak occupancy plus headroom, then verify the memory-versus-resize trade-off under realistic load.
Asymmetric equals can make insertion order matter: HashMap asks the new key whether it equals the key already in the bucket, so one direction may report equality while the reverse direction does not. The map can therefore retain two keys that the application considers logically identical, and lookups can vary depending on which key instance is used.
For a collision or matching hash, insertion of b tests approximately b.equals(a), not a symmetric equality check. Suppose a.equals(b) is true but b.equals(a) is false. If a is inserted first and then b, the second insertion sees false and creates another entry. A lookup using a may match the first entry, while a lookup using b may match the second. If the insertion order is reversed, the outcome can differ. Hash differences make the problem even less predictable because the entries may never reach the same bucket.
final class ParentKey {
final int id;
@Override public boolean equals(Object o) {
return o instanceof ParentKey p && id == p.id;
}
@Override public int hashCode() { return Integer.hashCode(id); }
}
// A subclass that defines equality only with itself can break symmetry.
// Prefer a final value key or one shared equality policy.
To diagnose and fix it:
a.equals(b) and b.equals(a) explicitly for every key implementation and subclass combination.instanceof versus exact-class checks, proxy classes, and generated equality methods with different policies.HashMap cannot enforce symmetry because equals is user-defined. In production, compare map size with the count of canonicalized business identities and inspect duplicate-key metrics at the boundary. The safest contract is symmetric, transitive, stable equality plus matching hashes for all key instances.
Interview takeaway: Because lookup uses the queried key's equality direction, asymmetric equals can create order-dependent duplicates; use one canonical, symmetric key type.
In current OpenJDK implementations, a heavily collided bin is treeified only when it reaches about eight entries and the table has capacity at least 64; otherwise the map prefers resizing. Treeification changes that bin to a red-black tree, but the thresholds are implementation details rather than a general HashMap API guarantee.
The relevant OpenJDK constants are TREEIFY_THRESHOLD 8, UNTREEIFY_THRESHOLD 6, and MIN_TREEIFY_CAPACITY 64. When a bin reaches the treeification threshold, HashMap first checks capacity. Below 64 it resizes instead, because a small table is more likely to be the cause of collisions. Once capacity is sufficient, the bin can become a tree. During resizing, a tree bin is split between the low and high destination bins; a resulting bin with few entries can be converted back to a linked list.
HashMap<Key, Value> map = new HashMap<>(64);
// This does not force treeification. It only avoids the
// small-table resize preference; collisions still depend on hashes.
map.put(key, value);
Important qualifications are:
For a collision problem:
hashCode quality and confirm that equal keys have equal hashes.Interview takeaway: Treeification is a collision safeguard shaped by both bin length and table capacity; correct hashing and sensible sizing remain the real fix.
ConcurrentHashMap makes merge atomic for a given key, so the read, remapping calculation, and replacement are coordinated instead of being split across separate get and put calls. It is the right tool when the update can be expressed as combining the existing value with a new value.
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(eventType, 1, Integer::sum);
The losing-increment pattern usually looks like get, calculate, then put: two threads can read 7, both calculate 8, and both store 8. merge arranges that the remapping function is applied against the current value for that key. The operation is atomic with respect to competing map updates for that key; it does not make a sequence of operations on several keys transactional. If no value exists, the supplied value is installed directly. If the remapping function returns null, the mapping is removed.
In production, look for:
get followed by arithmetic and put or replace.A safe fix is to:
merge(key, delta, Integer::sum) or a remapping function that is short, deterministic, and side-effect free.Long when the counter can exceed the range of Integer; the value type is still immutable and replaced atomically.The remapping function can be invoked while the map is coordinating updates, so it should not block or depend on unrelated map operations. For very hot counters, LongAdder may scale better than repeatedly replacing boxed integers, but it changes the consistency and retrieval trade-offs.
Interview takeaway: I would replace the split read-modify-write with merge for a per-key atomic update, while keeping the remapping function small and recognizing that it is not a multi-key transaction.
computeIfAbsent can throw IllegalStateException when its mapping function recursively tries to update the same key, because the map has reserved that key or bin while computing it and cannot safely complete the nested update. The restriction prevents a deadlock or an indefinitely recursive structural update.
ConcurrentHashMap<String, Config> configs = new ConcurrentHashMap<>();
// Do not do this inside the mapping function:
configs.computeIfAbsent("prod", key -> {
configs.put(key, loadFallback(key));
return loadPrimary(key);
});
Internally, a missing entry is represented by a reservation while the mapping function runs. Other threads encountering that reservation wait or retry according to the implementation, but a recursive operation by the computing thread cannot simply wait for itself to finish. Java's ConcurrentHashMap detects this class of recursive update and rejects it. The exact internal mechanics are implementation details, but the API contract also warns that the function must not modify this map during computation. A function that recursively calls computeIfAbsent for the same key is therefore invalid, and complicated callbacks can expose the same design error indirectly.
Useful production signals include:
IllegalStateException near cache initialization or lazy object construction.Fix it by:
computeIfAbsent, or use a separate map for a separate lifecycle.The operation is atomic for the targeted key, but the function may run only when the value is absent and should be written so repeated attempts are harmless. If construction itself requires cycle detection, use an explicit state machine or future-based design rather than recursive map mutation.
Interview takeaway: The exception is a safety signal: a computeIfAbsent mapping function must return a value, not recursively mutate the map it is populating.
A ConcurrentHashMap does not provide a transactionally consistent snapshot for logging. During concurrent updates, size() or mappingCount() can be transient and can disagree with an iteration, so I would treat the result as an observation or estimate, not as an exact audit total.
long observed = map.mappingCount();
logger.info("active entries observed={}", observed);
// Exact size requires coordination, for example quiescing writers first.
map.forEach((key, value) -> logger.debug("{}={}", key, value));
The map remains structurally safe: readers do not see a corrupt table, and operations on individual keys retain their specified concurrency guarantees. But one thread can add or remove mappings while size() traverses internal counters. mappingCount() returns a long and is useful when the count may exceed Integer.MAX_VALUE; it does not turn the result into a snapshot. A logging statement that prints size and then iterates is especially easy to misread because the two observations cover different moments.
Interpret the result this way:
isEmpty() can become stale immediately after it returns when writers remain active.For diagnosis and a fix:
If exactness matters for a report, copy entries while updates are paused or use a design that records immutable snapshots. Do not add a lock only around size() while writers ignore that lock; the coordination must cover both the writers and the snapshot operation.
Interview takeaway: I can rely on ConcurrentHashMap for safe access, but I call its changing size an observation unless writers are coordinated for an exact snapshot.
A ConcurrentHashMap iterator is weakly consistent: it does not throw ConcurrentModificationException, but it is not a snapshot. It may miss entries added after traversal reaches their bins, may see entries removed during traversal, and may observe some concurrent changes while missing others.
for (Map.Entry<String, Session> entry : sessions.entrySet()) {
String key = entry.getKey();
Session expected = entry.getValue();
if (expired(expected)) {
sessions.remove(key, expected); // do not delete a replacement
}
}
That behavior matters when deletion is based on an entry's value. The iterator may yield an expired session, then another thread may replace it with a fresh session before deletion. An unconditional remove(key) would delete the fresh value. The two-argument remove(key, value) performs a conditional removal, so the deletion succeeds only if the mapping still has the expected value. This protects replacement races, although the scan can still miss entries and therefore is not a complete purge by itself.
Typical failure signals are:
ConcurrentModificationException, leading someone to assume the iteration was a snapshot.Choose the policy explicitly:
An iterator is excellent for safe best-effort maintenance, not for a globally consistent delete-all operation. If deletion has external side effects, make those effects idempotent and expect a later pass to handle entries that were missed.
Interview takeaway: Treat a ConcurrentHashMap iterator as a moving view, and pair value-based cleanup with conditional removal so replacements are not accidentally deleted.
For a hot per-key counter, store a LongAdder as the value rather than repeatedly replacing an Integer or Long: ConcurrentHashMap<K, LongAdder>. LongAdder spreads concurrent increments across internal cells, reducing contention, while the map performs the one-time per-key object installation.
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent("checkout", key -> new LongAdder())
.increment();
long current = counts.getOrDefault("checkout", new LongAdder())
.sum();
With a boxed counter, every increment is a map-level read-modify-write and creates a new immutable number. Under a hot key, threads contend on that key's update path. LongAdder uses striped accumulation internally, so different threads can usually update different cells; sum() combines them. The map still needs computeIfAbsent to safely publish one adder for a missing key. The common pattern is especially useful when updates greatly outnumber reads.
The trade-offs are important:
sum() is not an atomic snapshot while increments continue; it is appropriate for metrics, not strict balances or limits.sumThenReset() is not a lossless transactional read-and-clear when concurrent updates must be assigned precisely to one reporting window.Validate the redesign by:
For exact increments, compare-and-set logic or a serialized ownership model may be more appropriate. LongAdder improves write scalability, but it does not provide a stronger consistency guarantee than its documented summation behavior.
Interview takeaway: I would use ConcurrentHashMap<K, LongAdder> for high-write metrics, provided an eventually observed sum is acceptable and the extra per-key memory is controlled.
Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
A TreeMap does not use equals to decide where a key belongs; it uses the comparator, or natural ordering when no comparator was supplied. If compare(k1, k2) is nonzero while k1.equals(k2) is true, an equal lookup key can follow a different path and miss the stored entry.
Comparator<UserId> byNumericId = Comparator.comparingInt(UserId::id);
// If equals also includes tenantId, this comparator is incomplete.
new TreeMap<UserId, User>(byNumericId);
The important consequences are:
TreeMap operations, regardless of equals.null, and containsKey can return false.equals uses several fields.Diagnose and fix it as follows:
compare(storedKey, lookupKey) alongside storedKey.equals(lookupKey) for a failing case.equals results.A comparator consistent with equals makes the collection contract predictable, but may produce a more complicated ordering. A separate business key can be clearer, at the cost of maintaining that canonicalization explicitly.
Interview takeaway: For a TreeMap, comparator equivalence is the key identity, so comparator and equals must describe the same identity unless the distinction is deliberate.
A mutable key can corrupt the ordering assumptions of a TreeMap: the node stays in the position chosen at insertion, while its current comparison result changes afterward. Consequently, get and remove can fail to find the same logical key—or appear to disagree—because each search follows the tree using the key’s current state.
final class AccountKey {
String region; // used by comparator, but mutable
long id;
}
TreeMap<AccountKey, String> map = new TreeMap<>(
Comparator.comparing((AccountKey k) -> k.region)
.thenComparingLong(k -> k.id));
What goes wrong:
get and remove use the same ordering logic; the apparent disagreement is not a supported map behavior.Use this production diagnosis and repair:
compare, or comparator-captured configuration, can change while the key is in the map.remove rather than relying on a possibly null value.Reinsertion repairs the tree but adds operational complexity and can briefly expose old or new state in concurrent code; TreeMap itself is not thread-safe. Immutability is usually the safer design.
Interview takeaway: A TreeMap stores a key at its old ordered position, so any field used for comparison must remain immutable while that key is present.
TreeMap.subMap applies the comparator to its boundary and candidate keys; it does not test boundary membership with equals. Therefore, an apparently equal boundary key can be excluded when it compares differently, or when the range is exclusive at that boundary.
TreeMap<String, Integer> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.put("alpha", 1);
NavigableMap<String, Integer> view = map.subMap("ALPHA", false,
"omega", true);
// "alpha" is excluded because compare("alpha", "ALPHA") == 0
// and the lower boundary is exclusive.
Check these common causes:
fromInclusive and toInclusive are independent flags; subMap(from, false, to, true) excludes the lower endpoint.equals does not.Diagnose the boundary precisely:
comparator.compare(candidate, from) and comparator.compare(candidate, to), using the map's comparator rather than equals.from is not greater than to in map order.If the business rule is an inclusive timestamp interval, for example, encode timestamps in a stable chronological order and define the endpoint policy explicitly. A comparator that collapses values may require a separate map or a multivalue structure when those values must remain distinguishable.
Interview takeaway: A submap boundary is included according to comparator result and its inclusive flag, never according to equals alone.
A TreeMap range is a contiguous interval in comparator order, not necessarily a range in the business meaning of the keys. If the comparator orders strings lexicographically, case-insensitively, in reverse, or by only one field, subMap will faithfully return that comparator interval—even when it looks surprising to the application.
TreeMap<String, Integer> map = new TreeMap<>(
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
// This is a length range, not an alphabetic range.
NavigableMap<String, Integer> range = map.subMap("aa", true,
"dddd", false);
Unexpected results commonly come from:
String.equals.To investigate a production result:
compare(entryKey, lower) and compare(entryKey, upper).Changing the comparator can make existing persisted assumptions or serialized data incompatible, and maintaining multiple indexes increases update cost and consistency risk. If the query has several independent dimensions, a TreeMap may be the wrong primary structure; filter a suitable candidate range or use a purpose-built index instead.
Interview takeaway: A TreeMap range query is correct only relative to the map's comparator, so the comparator must order keys by the dimension being queried.
When a comparator returns zero, TreeMap treats the two keys as the same key, even if they are distinct objects and equals returns false. A later put therefore updates the existing entry's value instead of adding a second entry; the original key object normally remains stored.
Comparator<String> byUserName = String.CASE_INSENSITIVE_ORDER;
TreeMap<String, Integer> counts = new TreeMap<>(byUserName);
counts.put("Alice", 1);
Integer old = counts.put("alice", 2);
// old == 1, counts.size() == 1, and the value is now 2
This behavior is often caused by:
Diagnose and choose the fix:
equals, hashCode, and comparator.compare; a zero result explains the overwrite.put and the map size to detect replacement rather than insertion.thenComparing as needed.Adding tie-breakers preserves distinct entries but makes ordering more detailed and may conflict with a deliberately case-insensitive lookup requirement. A TreeMap<Key, List<Value>> preserves grouped values, but callers must define duplicate handling and list update behavior.
Interview takeaway: In a TreeMap, comparator zero means key collision, so a zero result can replace a value even when equals says the objects are different.
HashMap iterators are fail-fast on a best-effort basis, not a concurrency-safety mechanism. They usually detect structural modification after iteration begins, but the Java specification does not guarantee that every unsynchronized modification will produce ConcurrentModificationException.
A typical iterator records the map's modification count when it is created. Each iterator operation compares that expected count with the map's current count. Adding or removing a mapping normally changes the count, so a mismatch is detected. Replacing the value for an existing key is not structural and normally does not change it.
A failure can be intermittent because:
To diagnose and fix it:
ConcurrentHashMap; if a stable view is required, copy the map under suitable synchronization before iterating.Do not catch and ignore ConcurrentModificationException. Even when no exception appears, unsynchronized concurrent use of HashMap remains incorrect.
Interview takeaway: Fail-fast iteration is an early-warning check, not a guarantee of detecting races or making HashMap thread-safe.
Iterator.remove() works because the iterator performs the removal through its own protocol and updates its expected modification state. Calling HashMap.remove() separately changes the map behind the iterator, leaving that iterator's state out of sync and eligible for ConcurrentModificationException.
The iterator remembers the last entry returned and, after a successful next(), can remove that exact mapping. The implementation removes it from the map and synchronizes the iterator's expected modification count with the map's new count. It also clears the last-returned state, so two consecutive removals without another next() are illegal.
for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
it.hasNext();) {
Map.Entry<String, Integer> entry = it.next();
if (entry.getValue() == 0) {
it.remove(); // supported
}
}
for (String key : map.keySet()) {
if (shouldRemove(key)) {
map.remove(key); // invalidates traversal
}
}
Important boundaries include:
Iterator.remove() is only valid once per returned element and only if that iterator supports removal.Use this decision path:
remove() method.removeIf on the appropriate collection view.Interview takeaway: Use the iterator's removal method because it updates both the collection and the iterator's expected state.
A ConcurrentHashMap iterator is weakly consistent: it does not represent a frozen snapshot, but it may reflect some changes made after iteration starts and may miss others, including a newly inserted entry. It does not throw ConcurrentModificationException merely because another thread updates the map.
The iterator traverses the table while other threads can insert, replace, or remove mappings. Its implementation provides safe concurrent access and avoids corrupting the data structure, but it does not promise one instant in time at which every returned entry existed. An insertion into a bucket already passed can be missed; an insertion into an unvisited area may be observed.
This consistency model means:
size(), isEmpty(), and aggregate observations can change while the traversal is running.Choose the behavior deliberately:
ConcurrentHashMap iteration for monitoring, cache inspection, dispatch, and other operations that tolerate an approximate moving view.compute, putIfAbsent, or remove(key, value) where appropriate.The key distinction is safety versus consistency: ConcurrentHashMap prevents structural corruption and provides defined concurrent access, but it intentionally does not provide snapshot iteration.
Interview takeaway: A ConcurrentHashMap iterator gives a safe moving view, not a transactionally complete snapshot.
Map.Entry.setValue() changes the value stored in an existing HashMap node, so it is normally a non-structural update and does not invalidate the iterator. Adding a new key changes the map's structure and modification count, so an iterator may detect it and throw ConcurrentModificationException.
A HashMap entry points to a node already located in a bucket, or in a tree bin in some implementations. Replacing that node's value does not move it, change the bucket layout, or alter the number of mappings. The iterator can therefore continue its traversal. A new key may add a node, trigger collision-bin changes, or cause resizing; those are structural changes.
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey().startsWith("retry-")) {
entry.setValue(entry.getValue() + 1); // supported
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
map.put("new-key", 1); // structural change
}
Keep these qualifications in mind:
HashMap access.For a safe update strategy:
entry.setValue for a single-threaded in-place value update during traversal.remove when deleting the current mapping.Interview takeaway: Value replacement preserves the map's structure, while adding a key changes the structure the iterator is traversing.
A mutable key can become unreachable in a HashMap: after a field used by equals or hashCode changes, the key may no longer hash to the bucket where its node was stored, or it may no longer compare equal to the lookup key. The entry remains physically present, but normal lookup can miss it.
HashMap computes the lookup key's hash, selects a bucket, and then compares candidate keys with equality. It does not relocate an existing entry when the key object changes. Thus put(key, value) followed by mutation can make get(key), containsKey(key), or remove(key) fail, even though iteration still displays the entry. If only a field used by equality changes, the old and new equality relationships can also violate the map's assumptions.
final class UserKey {
String tenant;
String username;
public int hashCode() {
return Objects.hash(tenant, username);
}
public boolean equals(Object o) {
return o instanceof UserKey k
&& Objects.equals(tenant, k.tenant)
&& Objects.equals(username, k.username);
}
}
UserKey key = new UserKey("a", "sam");
map.put(key, value);
key.username = "alex"; // entry is still in the old bucket
map.get(key); // may return null
Diagnose and fix it as follows:
Prefer an immutable value object or a Java record only when all components used by equality are themselves stable. The same principle applies to a TreeMap: mutating fields used by its comparator can make ordered lookup and removal unreliable.
Interview takeaway: A map key must remain equal to itself, with the same hash code, for as long as it is stored in the map.
HashMap should have stable fields for equals and hashCode for as long as it remains in the map.equals and hashCode contracts must describe the same logical identity, including for subclasses and custom key types.HashMap capacity from expected entries and load factor when avoiding resize-related latency matters.equals implementations can make logically equivalent keys behave differently depending on insertion and lookup direction.ConcurrentHashMap.merge, compute, or related atomic methods when an update must combine a value with the current mapping without a lost-update race.ConcurrentHashMap iterator is weakly consistent: it does not provide a snapshot and may reflect some, all, or none of concurrent changes.ConcurrentHashMap size observation is not a stable point-in-time fact while updates are occurring.TreeMap uses its comparator, or natural ordering, as the definition of key identity for lookup and replacement.HashMap traversal and trigger fail-fast behavior.Use an immutable key when its logical identity is known at construction and should not change while it is stored. A Java record is useful when its components naturally define equality and hashing, but its referenced objects must also have stable equality behavior. Immutability prevents bucket placement and tree ordering from becoming inconsistent after insertion; it does not fix a poorly chosen identity definition.
No. A synchronized wrapper typically serializes individual map operations using one monitor, while ConcurrentHashMap is designed for concurrent access with stronger throughput characteristics and atomic compound-operation methods such as compute and merge. Neither makes an arbitrary sequence of separate calls atomic. Choose based on the required consistency, contention, null-handling rules, and compound update semantics.
Test that the comparator is transitive, consistent with itself, and returns zero exactly when the map should treat two keys as the same ordering identity. Include boundary values, null policy if supported by the comparator, and objects that are equal according to equals but ordered differently. Also test range views, because their boundaries use comparator order rather than an unrelated business interpretation.
Changing an existing mapping's value through an iterator entry generally is not a structural modification for HashMap, so it does not normally invalidate that traversal. The operation still needs appropriate synchronization if other threads access the map. Adding or removing keys changes the map's structure and may trigger fail-fast behavior, which is a bug-detection aid rather than a concurrency guarantee.
For a single-threaded HashMap, use the iterator's remove method while traversing, or collect keys and remove them afterward. Do not structurally modify the map through a separate map reference during the same traversal. For concurrent designs, select an operation whose atomicity matches the rule, such as remove(key, value), and account for weakly consistent iteration.
Reliable collection code starts with explicit identity and ordering rules. Keep key state stable, make equals and hashCode agree, and ensure comparators reflect the identity that a TreeMap should use. For concurrent updates, prefer the map's atomic methods instead of read-then-write sequences, and treat iteration and size observations as limited views rather than snapshots. These principles explain most collection interview traps and provide practical guidance for designing maps that remain correct under mutation, resizing, collisions, and concurrent access.
Which question would you find the hardest? Tell me in the comments.
Core Java Interview Q&A with working code (200 Qs: OOP internals, concurrency, JVM, streams, JDK 8 to 25)
https://topmate.io/logicbrace/2288636
Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498
Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

0 Comments