Scrivio Interview library

HashMap and map implementations

37 questions in 11 subtopics.

Hashing and bucket index

InternalsFoundations7 min read
Walk through what java.util.HashMap does, from calling hashCode() to choosing a bucket, when you call map.put(key, value) in Java 8 or later.
CodingFoundations6 min read
A developer writes:
class Point {
final int x, y;
Point(int x, int y){
this.x=x;
this.y=y;
}
@Override
public boolean equals(Object o){
return o instanceof Point p && p.x==x && p.y==y;
}
}
and then
Map<Point,String> m = new HashMap<>();
m.put(new Point(1,2), "a");
System.out.println(m.get(new Point(1,2)));
What does this most likely print and how do you fix it?
ConceptIntermediate7 min read
HashMap keeps its table length a power of two and indexes with (n - 1) & hash instead of using a prime-sized table with hash % n. Explain the trade-off and the consequence for key classes with weak hashCode implementations.
LeadershipPrincipal8 min read
HashMap iteration order for some keys changed between Java 7 and Java 8, which broke many tests and some production code that depended on it. What does this say about relying on unspecified behaviour, and what practices would you require so future JDK upgrades do not break on such changes?

Collisions and treeification

InternalsFoundations7 min read
What happens inside a Java 8+ HashMap when many keys end up in the same bucket, and what lookup cost results?
DebuggingIntermediate7 min read
A profile of a service shows most CPU time in HashMap.getNode and in equals() of a key class OrderKey, with flame graph frames under HashMap$TreeNode.find. Maps hold about 200,000 entries. What do you suspect and how do you confirm and fix it?
ScenarioIntermediate7 min read
A public endpoint parses request JSON into a HashMap<String, Object>. A security review warns about hash-flooding: an attacker sending thousands of keys with the same String.hashCode(). How exposed is a Java 21 service, and what would you do?

Resize and load factor

InternalsFoundations6 min read
Explain how a Java 8+ HashMap resizes: the defaults, the trigger, and how entries move to the new table.
CodingFoundations6 min read
You need to load exactly 1,000 entries into a HashMap. A colleague writes new HashMap<>(1000). Does this avoid resizing? What would you write instead?
ConceptIntermediate7 min read
When would you change HashMap's load factor from 0.75, and what do you trade by going to 0.5 or to 1.0?
DebuggingIntermediate8 min read
An old service on Java 7 has occasional incidents where CPU goes to 100% and thread dumps show several request threads stuck in HashMap.get for minutes. After an upgrade to Java 17 the CPU spikes stop, but customers report missing entries. The map is a static HashMap updated from many threads. Explain both symptoms.
ScenarioAdvanced8 min read
Twelve services each load a reference-data HashMap of about 30 million entries at startup. Startup takes minutes, and heap usage briefly almost doubles during loading. What do you recommend across these services?

Null keys

ConceptFoundations6 min read
How does HashMap handle a null key and null values, and why do ConcurrentHashMap and Hashtable reject them?
DebuggingIntermediate7 min read
A team replaced HashMap with ConcurrentHashMap and Map.copyOf in several places for thread safety. After deployment, some requests fail with NullPointerException deep inside map code, and a cache that used computeIfAbsent seems to never store some keys. Explain the likely causes.

Mutable keys

DebuggingFoundations7 min read
A User object is added to a HashSet<User>. Later the code calls user.setEmail(newEmail), and hashCode() includes email. Now set.contains(user) returns false and set.remove(user) does nothing, but iterating the set still shows the user. Explain and fix.
ScenarioIntermediate7 min read
In a code review you see a JPA entity Order whose equals and hashCode use the generated database id. New orders are added to a HashSet<Order> on a parent before the parent is saved. What goes wrong and what would you recommend for entity equality?
DesignAdvanced7 min read
You own a shared domain library whose value types are used as HashMap keys, Caffeine cache keys and Redis cache keys by 20 services. Design the equality contract for these key types, including what happens when a field is added to a key class in a later version.

LinkedHashMap and LRU caches

ConceptFoundations6 min read
What ordering does LinkedHashMap keep, and what did Java 21's SequencedMap add to it?
CodingFoundations6 min read
Implement a simple LRU cache that holds at most 100 entries using LinkedHashMap, and explain what each constructor argument and overridden method does.
DesignIntermediate7 min read
A service uses a synchronized LinkedHashMap LRU cache for product lookups. At 20,000 requests per second, thread dumps show many threads BLOCKED on the cache monitor. Design a replacement and explain why the original contends.
LeadershipAdvanced6 min read
Across 40 services you find many hand-written LinkedHashMap and ConcurrentHashMap caches, some unbounded, some with custom eviction. Two recent incidents were OutOfMemoryErrors from such caches. What standard would you set and how would you roll it out?
LeadershipPrincipal7 min read
Over several years your services accumulated in-process map-based caches, a few distributed caches, and recurring incidents about stale data and memory. What long-term caching strategy would you set for the organisation, and how would you weigh its cost?

TreeMap and NavigableMap

InternalsFoundations6 min read
How does TreeMap decide that two keys are the same, and what problem appears when the comparator is inconsistent with equals?
CodingFoundations7 min read
Shipping fees depend on order total: 0 to 49.99 costs 7, 50 to 99.99 costs 4, 100 and above is free. Using a TreeMap<BigDecimal, BigDecimal> keyed by the lower bound, write the lookup and explain the NavigableMap method you used.
ScenarioIntermediate7 min read
You need to answer queries like "what was the configuration in effect at time t" and "all events between t1 and t2" for an in-memory store of a few million timestamped records that is mostly read and occasionally appended. Compare TreeMap, a sorted array with binary search, and ConcurrentSkipListMap.

WeakHashMap

ConceptFoundations6 min read
How does WeakHashMap decide when to remove an entry, and name two ways it surprises people.
ScenarioIntermediate7 min read
A teammate used a WeakHashMap<RequestDto, Result> as a cache for expensive computations, keyed by request DTOs created per request. The hit rate is near zero. Explain why and suggest a better design. Also say when WeakHashMap is the right tool.
ConceptPrincipal7 min read
Java has moved away from cleanup driven by garbage collection: finalization was deprecated for removal in Java 18 (JEP 421), with Cleaner, ClassValue and explicit close as the alternatives, while WeakHashMap remains. What does this tell you about building on GC-driven lifecycles, and what policy would you set?

IdentityHashMap

ConceptFoundations6 min read
What is IdentityHashMap, how is it implemented, and when is it the correct choice?
CodingIntermediate6 min read
You are writing a deepCopy(Object root) utility for an object graph that may contain cycles and shared references. Describe how you would use IdentityHashMap and why HashMap would be wrong.

HashCode quality

CodingFoundations7 min read
Review these hashCode implementations for a Point(int x, int y) used as a HashMap key: (a) return 1; (b) return x + y; (c) return Objects.hash(x, y). What is wrong with each, if anything?
DebuggingIntermediate6 min read
After a refactor, OrderKey.hashCode() was changed to return region.hashCode() because region is "the main field". There are only 6 regions and millions of keys. Latency of a lookup-heavy path rose tenfold. Explain the mechanism and how you would prevent such a regression.
DesignAdvanced7 min read
Your platform team maintains shared libraries used by many services, and several incidents came from key classes with bad equals and hashCode. What conventions for value objects used as map keys or cache keys would you set across teams, and how would you enforce them?
LeadershipPrincipal7 min read
Java 7u6 added an optional alternative String hashing for HashMap to resist collision attacks, and Java 8 removed it in favour of treeifying large bins (JEP 180). Other languages chose per-process randomized hashing. What does this decision show about how Java weighs compatibility, and how should it shape your own platform decisions?

Common map operations

CodingFoundations6 min read
Using Map methods added in Java 8 and later, write code that counts words in a List<String>, groups orders by customer into Map<Long, List<Order>>, and gets a value with a default. Which methods would you use and what are their pitfalls?
DebuggingIntermediate6 min read
This code builds a Map with streams and fails in production with IllegalStateException: Duplicate key 17 (attempted merging values ...): products.stream().collect(Collectors.toMap(Product::categoryId, Product::name)). Another version fails with NullPointerException. Explain both and fix them.
LeadershipAdvanced6 min read
Code reviews across teams keep finding the same map misuse: containsKey followed by get, mutable maps exposed from APIs, and maps used as ad hoc objects. What guidance and tooling would you introduce?