Senior Java Collections Interview Questions – Top 20 with Answers

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 guide

Section 1: HashMap Internals

1. A HashMap lookup fails after a key field changes. How do you prevent this bug?

Treat 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:

  1. Check whether the key is mutable, including mutable objects nested inside a supposedly final field.
  2. Compare the key's hash before insertion with its hash when lookup fails; inspect the equality fields as well.
  3. Use immutable value objects, defensive copies, or a canonical immutable identifier as keys.
  4. If mutation is required, call 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.

2. Why must a custom key's equals and hashCode use the same immutable fields?

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:

  • A get or containsKey miss despite an entry appearing to exist.
  • A HashSet containing what appear to be duplicate values, or a failed remove.
  • Behavior changing after an object is updated, or after serialization and reconstruction.

Review a custom key by:

  1. Writing tests for reflexivity, symmetry, transitivity, and consistency, plus the implication that equal objects have equal hashes.
  2. Listing exactly which fields define identity and excluding mutable business state, timestamps, caches, and associations.
  3. Checking nested identity fields: a final reference is not enough if the referenced object is mutable.
  4. Using a canonical immutable key, or copying the required values into one at the map boundary.

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.

3. How can HashMap resizing create latency spikes, and how would you plan capacity?

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:

  1. Estimate the peak live entries, not the average, and include headroom for bursts.
  2. Choose ceil(expectedEntries / loadFactor) as the conceptual minimum; HashMap rounds the table to an implementation-appropriate power of two.
  3. Verify memory impact in a load test, because an oversized table costs space and can worsen cache locality.
  4. Warm or populate the map before serving latency-sensitive traffic when practical, and monitor growth rather than relying on a guess.

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.

  • Too small: repeated growth and bursty insertion latency.
  • Too large: higher retained memory and potentially poorer locality.
  • Unbounded: capacity planning only delays the problem; enforce an eviction or size policy where appropriate.

Interview takeaway: Size a HashMap for peak occupancy plus headroom, then verify the memory-versus-resize trade-off under realistic load.

4. A HashMap stores duplicate logical keys. How can asymmetric equals cause this?

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:

  1. Test a.equals(b) and b.equals(a) explicitly for every key implementation and subclass combination.
  2. Look for inheritance, instanceof versus exact-class checks, proxy classes, and generated equality methods with different policies.
  3. Replace polymorphic keys with a final value object or a canonical representation containing the required type and identity.
  4. Remove existing duplicate entries and rebuild the map after deploying the corrected key; changing the class does not repair old contents.

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.

5. How does HashMap treeification depend on table capacity and collision thresholds?

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:

  • The threshold counts entries in one bin, not the map's total size.
  • Poor or deliberately colliding hashes are required; a large map does not automatically treeify.
  • Tree nodes use ordering information where available, with tie-breaking rules when keys are not mutually comparable, so treeification is not a substitute for a correct hash function.
  • A resize can happen before or around treeification, changing the bin distribution and observed timing.

For a collision problem:

  1. Inspect hashCode quality and confirm that equal keys have equal hashes.
  2. Use profiling or a heap dump to identify oversized bins; do not infer collision rates from map size alone.
  3. Fix the key hash or choose a suitable key representation before tuning capacity.
  4. Only pre-size the table when profiling shows predictable occupancy; do not try to tune internal thresholds, which are not supported configuration knobs.

Interview takeaway: Treeification is a collision safeguard shaped by both bin length and table capacity; correct hashing and sensible sizing remain the real fix.

Section 2: ConcurrentHashMap Behavior

6. ConcurrentHashMap updates lose increments. How would merge avoid that race?

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:

  • Counters lower than the number of accepted events, especially under load.
  • A method containing get followed by arithmetic and put or replace.
  • A remapping function that performs slow I/O, calls back into the same map, or has observable side effects.

A safe fix is to:

  1. Use merge(key, delta, Integer::sum) or a remapping function that is short, deterministic, and side-effect free.
  2. Use Long when the counter can exceed the range of Integer; the value type is still immutable and replaced atomically.
  3. Use an external transaction or coordinated protocol if the update must cover multiple keys or another system.

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.

7. Why can ConcurrentHashMap.computeIfAbsent reject recursive updates on one key?

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.
  • Thread dumps showing threads waiting around map initialization.
  • A mapping function that calls a helper which writes to the same map, often hidden behind event publication or fallback logic.

Fix it by:

  1. Make the mapping function only construct and return the value; perform map mutation outside it if needed.
  2. Precompute dependencies before entering computeIfAbsent, or use a separate map for a separate lifecycle.
  3. Keep the function quick and avoid blocking calls, callbacks, and recursive cache population.

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.

8. A ConcurrentHashMap size changes during logging. Which result can you safely rely on?

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:

  • It is safe as a current operational signal, such as detecting that the map is broadly populated.
  • It is not safe for an exact report, reconciliation total, or decision that assumes no concurrent changes.
  • Even isEmpty() can become stale immediately after it returns when writers remain active.

For diagnosis and a fix:

  1. Record the map count, writer activity, and timestamp together, and label the count as observed if updates are active.
  2. Use a separate atomic metric maintained by the write path when an application-level event count is needed.
  3. Quiesce writers, or coordinate through a lock or ownership protocol, before taking an exact snapshot.

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.

9. How can weakly consistent ConcurrentHashMap iterators affect deletion logic?

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:

  • Expired records surviving one cleanup pass.
  • Fresh records disappearing after a timeout or eviction scan.
  • Cleanup tests passing when single-threaded but failing under replacement or insertion load.
  • No ConcurrentModificationException, leading someone to assume the iteration was a snapshot.

Choose the policy explicitly:

  1. Use conditional removal when the decision depends on the value observed by the iterator.
  2. Run repeated scans, partition cleanup, or use scheduled expiration when eventual cleanup is acceptable.
  3. Stop or coordinate writers before a one-pass exact deletion, or move expiration into an operation that checks the key and value atomically.

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.

10. A hot key overloads one counter. How can LongAdder change the map design?

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.
  • Each key now retains a mutable, potentially multi-cell object, increasing memory use compared with one boxed number.
  • sumThenReset() is not a lossless transactional read-and-clear when concurrent updates must be assigned precisely to one reporting window.

Validate the redesign by:

  1. Confirming the value is a metric or approximate live total rather than a correctness-critical quota.
  2. Measuring contention and allocation before and after, including the number of distinct keys.
  3. Reading counters at reporting boundaries and removing idle adders with an explicit lifecycle policy if key growth is unbounded.

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)

Section 3: TreeMap Ordering

11. TreeMap misses a key that equals considers equal. How can comparator order cause it?

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:

  • A comparator result of zero means “the same map key” for TreeMap operations, regardless of equals.
  • If equal objects compare nonzero, the map may contain two keys that application code considers equal.
  • A lookup using an equal-but-differently-ordered instance can return null, and containsKey can return false.
  • This often appears after adding a comparator that orders by one field while equals uses several fields.

Diagnose and fix it as follows:

  1. Log the comparator class and evaluate compare(storedKey, lookupKey) alongside storedKey.equals(lookupKey) for a failing case.
  2. Check the actual entries in comparator order; do not inspect only hash codes or equals results.
  3. Make the comparator consistent with equality, normally by comparing every identity-defining field in the same semantic way.
  4. If the business lookup intentionally uses a different identity, use a separate key type or canonicalize the lookup before inserting and reading.

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.

12. Why can a mutable TreeMap key make get and remove disagree?

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:

  • Insertion places the node according to the key's old region and id.
  • After mutation, searching with that key uses its new region and id, but the node is still in the old branch.
  • A lookup may accidentally find another node, miss entirely, or work for one key state and fail for another.
  • With a stateful or inconsistent comparator, calls made at different times can legitimately produce different results. With the same stable comparator and unchanged key state, get and remove use the same ordering logic; the apparent disagreement is not a supported map behavior.

Use this production diagnosis and repair:

  1. Capture the key before and after mutation, and log comparator results against neighboring entries or a freshly constructed equivalent key.
  2. Check whether fields used by compare, or comparator-captured configuration, can change while the key is in the map.
  3. Remove the entry before changing its sort fields, then insert it again; verify the return value from remove rather than relying on a possibly null value.
  4. Prefer immutable keys with final identity and ordering fields. If mutation is required, use a stable key and store changing attributes only in the 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.

13. Why can TreeMap.subMap exclude a boundary key unexpectedly?

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.
  • A comparator may treat case, accents, whitespace, numeric formatting, or multiple objects as equivalent even when equals does not.
  • A comparator may place the candidate on the other side of the boundary, especially with reverse or descending order.
  • The returned object is a live range view, so later inserts and removals in the backing map can change what the view contains.

Diagnose the boundary precisely:

  1. Evaluate comparator.compare(candidate, from) and comparator.compare(candidate, to), using the map's comparator rather than equals.
  2. Record the exact inclusivity flags and confirm that from is not greater than to in map order.
  3. Test boundary values in a small unit test, including distinct objects that compare to zero and values differing only in normalization.
  4. Choose inclusive flags deliberately, or change the comparator/key representation so its order matches the range semantics.

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.

14. A TreeMap range query returns unexpected entries. How would comparator order explain it?

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:

  • A comparator that sorts by length, status, tenant, or a truncated prefix before comparing the full key.
  • Reverse order, where “lower” and “higher” have the opposite meaning from natural order.
  • Case-folding, locale-sensitive comparison, or normalization that groups values differently from String.equals.
  • A range boundary whose representation is not a meaningful lower or upper bound under the comparator.

To investigate a production result:

  1. Obtain the exact comparator and log each boundary comparison: compare(entryKey, lower) and compare(entryKey, upper).
  2. Print entries using iteration order; that order reveals the interval that the map actually understands.
  3. Verify whether the comparator is deterministic and consistent with its documented ordering, including locale or configuration changes.
  4. Align the index with the query: use a comparator that orders by the queried dimension, or maintain another map/index for a different dimension.

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.

15. Why can a comparator returning zero for distinct keys overwrite values?

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:

  • Case-insensitive or trimmed text comparison.
  • Comparing only an ID while objects also contain tenant, version, or type fields.
  • A comparator that intentionally rounds numbers or compares only a prefix.
  • A missing tie-breaker in a chained comparator.

Diagnose and choose the fix:

  1. For two keys that unexpectedly collide, log equals, hashCode, and comparator.compare; a zero result explains the overwrite.
  2. Check the return value of put and the map size to detect replacement rather than insertion.
  3. If both objects must be distinct, add every identity field to a deterministic comparator, using thenComparing as needed.
  4. If they are genuinely one business identity, keep the comparator and document the replacement semantics; use a collection value when multiple records belong to that identity.

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.

Section 4: Iterator Traps

16. A HashMap iterator throws ConcurrentModificationException only sometimes. Why is fail-fast limited?

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:

  • The modification happens after the iterator has already passed the affected area.
  • The racing thread's update is not observed at the exact check; unsynchronized access has no reliable visibility or ordering guarantee.
  • The code modifies the map through a path that is not reached before the iteration ends.
  • The iterator detects the change later than the actual mutation, so the exception is a debugging signal rather than a precise report of the offending line.

To diagnose and fix it:

  1. Capture the exception stack trace and identify every possible writer, not only the reader shown in the trace.
  2. Check whether the map is shared across request threads, callbacks, executors, or listeners.
  3. Use one lock consistently around both iteration and mutation, or confine the map to one thread.
  4. If concurrent access is required, choose 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.

17. Why can Iterator.remove work while HashMap.remove can invalidate traversal?

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.
  • A direct removal may appear to work in a short loop, but the next iterator operation can detect the mismatch.
  • Changing an existing value is not structural, but adding or removing a key is.
  • This is still not safe when another thread mutates the map concurrently.

Use this decision path:

  1. For one-pass filtering, use the iterator's remove() method.
  2. For a condition that can be expressed directly, use removeIf on the appropriate collection view.
  3. For concurrent mutation, establish synchronization or use a collection designed for concurrent access; do not rely on iterator behavior.

Interview takeaway: Use the iterator's removal method because it updates both the collection and the iterator's expected state.

18. A ConcurrentHashMap iterator misses a new entry. What consistency does that permit?

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:

  • Returned entries are never normally duplicated by one iterator traversal.
  • The iterator does not guarantee that every entry present at creation, or at any later instant, is returned.
  • A removal may prevent an entry from being returned, while a concurrent replacement may be observed as either value depending on timing.
  • size(), isEmpty(), and aggregate observations can change while the traversal is running.

Choose the behavior deliberately:

  1. Use ConcurrentHashMap iteration for monitoring, cache inspection, dispatch, and other operations that tolerate an approximate moving view.
  2. If processing every entry from a stable point matters, copy entries into another collection at a defined synchronization boundary.
  3. If a compound rule must be atomic, use an atomic map operation such as compute, putIfAbsent, or remove(key, value) where appropriate.
  4. Test with concurrent writers; a single-threaded test cannot prove snapshot behavior.

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.

19. Why can entry.setValue work during HashMap iteration while adding a key can fail?

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:

  • The entry must come from the map's entry-set view; an arbitrary entry object may not be writable.
  • Replacing a value does not make compound read-modify-write logic thread-safe.
  • A value object can itself be mutable, and changing it may affect application behavior without changing the map structure.
  • Whether an exception appears is not a license for unsynchronized concurrent HashMap access.

For a safe update strategy:

  1. Use entry.setValue for a single-threaded in-place value update during traversal.
  2. Use the iterator's remove when deleting the current mapping.
  3. Collect keys to add or remove and apply structural changes after the loop, or use a concurrent map when genuine concurrent access is required.
  4. Synchronize the complete read-and-update sequence when the result depends on other threads.

Interview takeaway: Value replacement preserves the map's structure, while adding a key changes the structure the iterator is traversing.

20. A custom key works in tests but misses in production. How can mutable fields break equality?

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:

  1. Log the key's relevant fields and hash at insertion, lookup, and removal; compare those with an iteration dump of the map.
  2. Trace setters, ORM hydration, reflection, and reused request objects that can mutate the key after insertion.
  3. Make keys immutable, including immutable state inside fields used by equality; defensive copies may be needed for arrays or collections.
  4. If a key must change, remove it before mutation and reinsert it afterward, while preventing concurrent access during that sequence.

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.

  • Use immutable components for nested fields such as lists, arrays, or date-like objects, or defensively copy them before storing them in the key.
  • When diagnosing production misses, compare both the key's current field values and its current hash with the values captured when the entry was inserted.

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.

Key Takeaways

  • A key used in a HashMap should have stable fields for equals and hashCode for as long as it remains in the map.
  • The equals and hashCode contracts must describe the same logical identity, including for subclasses and custom key types.
  • Plan HashMap capacity from expected entries and load factor when avoiding resize-related latency matters.
  • Asymmetric equals implementations can make logically equivalent keys behave differently depending on insertion and lookup direction.
  • HashMap treeification is influenced by both collision thresholds and the table's minimum capacity, not just by the number of colliding entries.
  • Use ConcurrentHashMap.merge, compute, or related atomic methods when an update must combine a value with the current mapping without a lost-update race.
  • A ConcurrentHashMap iterator is weakly consistent: it does not provide a snapshot and may reflect some, all, or none of concurrent changes.
  • A ConcurrentHashMap size observation is not a stable point-in-time fact while updates are occurring.
  • A TreeMap uses its comparator, or natural ordering, as the definition of key identity for lookup and replacement.
  • Iterator removal has traversal-specific support, while structural changes through the map can invalidate a HashMap traversal and trigger fail-fast behavior.

Frequently Asked Questions

When should a key be a record or another immutable type?

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.

Is a synchronized map equivalent to `ConcurrentHashMap`?

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.

How should a comparator be tested for a `TreeMap`?

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.

Can changing a value during map iteration be considered safe?

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.

What is the safest way to remove entries while scanning a map?

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.

Conclusion

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.

Explore More Java Interview Resources

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

Senior Java Collections Interview Questions – Top 20 with Answers

Post a Comment

0 Comments

Close Menu