Java Design, Scaling, and Testing Follow-Ups
Hard · Software Engineering Fundamentals · Software Engineer · Onsite
Prompt
Suppose you have just finished coding an algorithmic solution in Java during an onsite interview, and the interviewers pivot to production-focused follow-ups and requirement changes. Explain how you approach each area below — including concrete code-level adjustments where appropriate:
- Requirement changes and refactoring: Adapting a working implementation when rules shift (such as a new input encoding, stricter validation, deterministic tie-breaking, or a richer return object) without sacrificing readability or testability.
- Scaling to large inputs: Evaluating asymptotic runtime, JVM heap layout, object-allocation overhead, and I/O bottlenecks when input volume increases by orders of magnitude, along with practical optimizations.
- Data-structure selection: Choosing among standard JDK collections (
ArrayList,LinkedList,ArrayDeque/Deque,Stack,HashMap,LinkedHashMap,TreeMap,PriorityQueue,ConcurrentHashMap) and steering clear of common Java collection bugs. - Parameterized types (generics): How generics operate under the hood in Java, including type erasure, invariance, bounded wildcards (
extends/super), and design trade-offs. - Error and exception modeling: Distinguishing checked from unchecked exceptions, following clean throw/catch practices, and handling malformed or out-of-range inputs safely.
- Automated testing: Designing a JUnit test suite that verifies boundary inputs, invalid-data behavior, and non-regression as new requirements land.
Scope & Expectations
- Ground your discussion in realistic Java code and concrete JVM behavior (such as object headers, autoboxing, and collection internals) rather than abstract definitions alone.
- Show how to evolve code incrementally into small, single-responsibility methods with explicit domain types and deterministic contracts.
- Cover subtle JDK pitfalls across collections, generics, numeric overflow, resource management, and edge-case testing.
Step-by-step walkthrough
Anchor every follow-up in one concrete Java solution
Follow-up rounds go best when you tie every answer directly to the code on your screen rather than reciting abstract textbook definitions. Let's use one realistic running problem throughout all six areas:
Given payment settlements as
(merchantId, amountCents), return thekmerchants with the highest net balance.Here is a typical working first draft written under time pressure (Java 17+):
import java.util.*; public final class TopMerchants { public static List<String> topK(String[] merchants, long[] amounts, int k) { Map<String, Long> totals = new HashMap<>(); for (int i = 0; i < merchants.length; i++) { totals.merge(merchants[i], amounts[i], Long::sum); } List<String> keys = new ArrayList<>(totals.keySet()); keys.sort((a, b) -> Long.compare(totals.get(b), totals.get(a))); return keys.subList(0, Math.min(k, keys.size())); } }Before the interviewer even asks, point out four production weaknesses hiding inside this prototype:
- Unspecified tie-breaking: when two merchants share the same balance, their relative order comes from
HashMapbucket iteration order, which is unspecified and can change across JDK versions or resizes. - Missing input validation: if
amounts.length < merchants.length, the loop throws a rawArrayIndexOutOfBoundsException; worse, ifamounts.length > merchants.length, extra settlements are silently ignored. Passingk < 0throws anIllegalArgumentExceptiondeep insidesubListwith an unhelpful message. List.subListview retention:keys.subList(0, k)returns a live view backed by the entirekeyslist rather than an independent copy — returning 10 winners prevents garbage-collecting a 1,000,000-element backing list, and mutatingkeyslater triggersConcurrentModificationException.- Autoboxing and object churn: autoboxing (Java automatically wrapping a primitive
longinside a heap-allocatedjava.lang.Longobject) allocates newLongwrappers on updates outside the tiny-128..127cache, plus oneHashMap.Nodeobject per distinct merchant.
- Unspecified tie-breaking: when two merchants share the same balance, their relative order comes from
Refactoring for changing requirements
Suppose the interviewer introduces a change request: Input now arrives as CSV strings
"merchant,amount"with decimal dollars like"M_GAMMA,12.00"; reject malformed lines with their line number; break ties alphabetically by merchant ID; and return both the merchant ID and its total.Resist the urge to delete everything and rewrite one giant loop. Instead, follow a disciplined 5-step sequence:
- Clarify edge-case rules first: can amounts be negative (chargebacks/refunds)? Should
"1.005"(sub-cent precision) fail? Should one corrupt row abort the whole batch or be skipped and logged? - Pin existing behavior with tests before editing so refactoring cannot silently break working logic.
- Decompose into pure stages (
parse -> aggregate -> rank): each method does one job and can be unit-tested without files or mocks. If tomorrow's requirement switches CSV to JSON, onlyparseLinechanges. - Encode invariants in types: replace parallel arrays with Java
records (compact immutable data classes that automatically generateequals,hashCode, andtoString), and keep money in exactlongcents (doublebinary floating point cannot represent0.10exactly, and 32-bitintcents overflow at2,147,483,647cents ≈$21.47M). - Preserve backward compatibility if callers already exist by keeping the old signature as a thin
@Deprecatedwrapper delegating to the new pipeline.
import java.math.BigDecimal; import java.util.*; public record Settlement(String merchant, long amountCents) {} public record MerchantTotal(String merchant, long totalCents) {} public final class TopMerchants { // Deterministic total order: highest balance first, then alphabetical merchant ID. static final Comparator<MerchantTotal> BEST_FIRST = Comparator.comparingLong(MerchantTotal::totalCents).reversed() .thenComparing(MerchantTotal::merchant); static Settlement parseLine(String line, int lineNo) { if (line == null || line.isBlank()) { throw new InvalidRecordException(lineNo, "empty line"); } // Limit -1 preserves trailing empty fields so "m_alpha," splits into ["m_alpha", ""]. String[] parts = line.split(",", -1); if (parts.length != 2) { throw new InvalidRecordException(lineNo, "expected 2 fields, got " + parts.length); } String merchant = parts[0].trim(); if (merchant.isEmpty()) { throw new InvalidRecordException(lineNo, "empty merchant id"); } try { // "12.00" -> 1200L; "1.005" throws ArithmeticException instead of silently rounding. long cents = new BigDecimal(parts[1].trim()).movePointRight(2).longValueExact(); return new Settlement(merchant, cents); } catch (NumberFormatException | ArithmeticException e) { throw new InvalidRecordException(lineNo, "invalid amount '" + parts[1] + "'", e); } } static Map<String, Long> aggregateTotals(List<Settlement> settlements) { Objects.requireNonNull(settlements, "settlements must not be null"); Map<String, Long> totals = new HashMap<>(); for (Settlement s : settlements) { // Math::addExact throws ArithmeticException rather than wrapping around on overflow. totals.merge(s.merchant(), s.amountCents(), Math::addExact); } return totals; } static List<MerchantTotal> topK(Map<String, Long> totals, int k) { Objects.requireNonNull(totals, "totals must not be null"); if (k < 0) { throw new IllegalArgumentException("k must be >= 0, got " + k); } if (k == 0 || totals.isEmpty()) { return List.of(); } List<MerchantTotal> all = new ArrayList<>(totals.size()); for (Map.Entry<String, Long> e : totals.entrySet()) { all.add(new MerchantTotal(e.getKey(), e.getValue())); } all.sort(BEST_FIRST); // Copy out of subList so the huge backing list can be garbage-collected immediately. return new ArrayList<>(all.subList(0, Math.min(k, all.size()))); } }- Clarify edge-case rules first: can amounts be negative (chargebacks/refunds)? Should
Scaling to large datasets on the JVM
Quantify scale with concrete numbers: suppose we process
n = 10^8CSV lines (~2.5 GB) spanningm = 10^6distinct merchants, withk = 10.- Time complexity: streaming and aggregating into
HashMaptakesO(n)average time. Sorting allmmerchants takesO(m log m)(~10^6 × 20 ≈ 2 × 10^7comparisons, under 0.2 seconds), while maintaining a bounded size-kmin-heap takesO(m log k)(~10^6 × 3.3operations) and avoids allocating anm-elementArrayList. Disk I/O, string allocation, and JVM heap footprint — not sorting — dominate runtime. - JVM memory math (64-bit HotSpot with compressed 4-byte references,
-XX:+UseCompressedOops): every Java heap object carries a 12-byte object header (JVM lock/GC metadata + class pointer) and is padded to an 8-byte multiple:
Per distinct merchant in HashMap<String, Long> (m = 1,000,000): HashMap.Node 12B header + 4B hash + 3 x 4B refs = 28B -> 32 bytes Boxed Long value 12B header + 8B long (+4B align) -> 24 bytes String "MERCH00001" 24B String wrapper + 32B byte[10] array -> 56 bytes Node[] table array 2^21 slots (0.75 load) x 4B / 10^6 keys -> ~ 8 bytes Total ~ 120 bytes/key 10^6 merchants in HashMap<String, Long> ~ 120 MB 10^6 merchants in primitive long[] = 8 MB (15x smaller!)Targeted optimizations to propose, ordered by impact:
- Stream line by line: read with
Files.newBufferedReader(path)so only one line lives in young-generation RAM at a time;Files.readAllLineswould materialize10^8Strings (> 5.6 GB) and crash withOutOfMemoryError. - Eliminate boxing and node wrappers: if merchant IDs map to dense integers (
"MERCH00042" -> 42), accumulate into a flatlong[](8 MB, zero GC churn). For arbitrary string IDs, an open-addressed primitive map (like FastUtil'sObject2LongOpenHashMap) stores keys in a flatObject[]and totals in a parallellong[], cuttingNodeandLongallocations completely. - Bound ranking memory to
O(k)with a min-heap: keep only the strongestkmerchants in aPriorityQueueordered worst-first so the weakest top-kcandidate sits atpeek()ready for eviction:
static List<MerchantTotal> topKWithHeap(Map<String, Long> totals, int k) { if (k < 0) { throw new IllegalArgumentException("k must be >= 0, got " + k); } // Guard k == 0 upfront: zero heap work, and new PriorityQueue<>(0, ...) would throw! if (k == 0 || totals.isEmpty()) { return List.of(); } // Reversed comparator puts the weakest of the current top-k at the root for O(log k) eviction. PriorityQueue<MerchantTotal> minHeap = new PriorityQueue<>(k + 1, BEST_FIRST.reversed()); for (Map.Entry<String, Long> e : totals.entrySet()) { minHeap.offer(new MerchantTotal(e.getKey(), e.getValue())); if (minHeap.size() > k) { minHeap.poll(); } } // Iterating a PriorityQueue does NOT yield sorted order — copy and sort the k winners. List<MerchantTotal> winners = new ArrayList<>(minHeap); winners.sort(BEST_FIRST); return winners; }- Out-of-core partitioning when
mexceeds RAM: hash-partition incoming lines intoPspill files byMath.floorMod(merchant.hashCode(), P)so every settlement for the same merchant lands in the same file, aggregate each file independently in memory, and merge thePtop-klists. Always measure first with Java Flight Recorder (JFR), GC logs (-Xlog:gc), and JMH (Java Microbenchmark Harness, which accounts for JIT warm-up).
- Time complexity: streaming and aggregating into
Selecting Java collections and avoiding classic traps
Justify every collection by matching required operations to underlying memory layout:
Access Pattern Best Choice Complexity Why It Wins Sequential list / index lookup ArrayListgetO(1), append amortizedO(1), middle removeO(n)Contiguous Object[]gives fast CPU cache locality; defaultList.LIFO stack or FIFO queue ArrayDequepush/pop/offer/pollamortizedO(1)Circular array; beats legacy synchronizedStackand node-heavyLinkedList(forbidsnull).Frequent middle splice at a known cursor LinkedList(rare)O(1)viaListIterator,O(n)get(i)Allocates a 24-byte Nodeper item and scatters pointers in RAM; almost never faster thanArrayList.Unordered key -> value lookup HashMap/HashSetO(1)average,O(log n)worst-case bucket (Java 8+ treeify)Hash table; converts collided chains ( >= 8nodes, table>= 64) to red-black trees when keys areComparable.Insertion-ordered map or bounded LRU cache LinkedHashMapO(1)averageHashMap+ doubly linked list across entries (accessOrder=true+removeEldestEntrybuilds an LRU cache).Sorted keys & range queries TreeMap/TreeSetO(log n)lookup/insert/rangeRed-black balanced binary search tree supporting floorKey,ceilingKey, andsubMap.Repeated min / max extraction PriorityQueueoffer/pollO(log n),peekO(1)Array-backed binary heap (note: remove(Object)isO(n)linear scan).Multi-threaded key aggregation ConcurrentHashMapO(1)average under contentionFine-grained per-bin locking + CAS atomic merge/compute(forbidsnullkeys and values).Classic Java collection pitfalls interviewers test: - Mutating a
HashMapkey after insertion: changing a field used byhashCode()strands the entry in the wrong bucket forever — always use immutable keys (String,record). - Breaking theequals/hashCodecontract: overridingequalswithouthashCodeputs equal keys in different hash buckets. - Overload trapList<Integer>.remove(1): callsremove(int index)(deletes element at index1), whereasremove(Integer.valueOf(1))deletes the value1. - Boxed==reference comparison:Integer a = 1000, b = 1000; a == bevaluates tofalsebecauseInteger.valueOfonly caches-128..127by default — always compare objects with.equals()or unbox to primitives. - Subtraction comparator overflow:(a, b) -> a - boverflows whena = Integer.MIN_VALUEandb = 1; always useInteger.compare(a, b)orLong.compare(a, b). -TreeMapcomparator inconsistent withequals:TreeMapdecides key equality solely bycompare(a, b) == 0, so sorting merchants only by balance in aTreeMapsilently overwrites tied merchants!Java generics: type erasure, invariance, and PECS wildcards
Generics let you parameterize types (
List<String>) so the compiler catches type mismatches at compile time instead of crashing later at runtime. To stay binary-compatible with pre-Java-5 bytecode, Java implements generics via type erasure: during compilation, the compiler checks every type constraint, erases<T>toObject(or its upper bound likeComparable), and inserts explicit casts at read sites.Source code (compile time) Bytecode after type erasure (runtime) ------------------------------- ------------------------------------- List<String> ids = new ArrayList<>(); List ids = new ArrayList(); ids.add("m_alpha"); ids.add("m_alpha"); String s = ids.get(0); String s = (String) ids.get(0);Direct consequences of type erasure: -
new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass()istrue(both areArrayList.class). - You cannot writenew T(),new T[10], orobj instanceof List<String>(pass aClass<T>token orIntFunction<T[]>array factory when needed), nor can you overloadvoid handle(List<String>)alongsidevoid handle(List<Integer>)(identical erased signaturehandle(List)). - Type arguments cannot be primitives (List<int>does not compile), forcing boxedList<Integer>overhead.Invariance and PECS wildcards (
Producer extends, Consumer super): Java generics are invariant:List<Integer>is not a subtype ofList<Number>(otherwise someone could add aDoubleinto anIntegerlist). By contrast, Java arrays are covariant (Object[] arr = new String[1]; arr[0] = 42;), which compiles cleanly and crashes at runtime withArrayStoreException. To write flexible APIs safely, use bounded wildcards: -? extends T(Producer): safe to readTvalues out (you cannot safely add items because the exact subtype is unknown). -? super T(Consumer): safe to writeTvalues in (used for comparators and output collections).Applying PECS generalizes our ranking helper to any key type
Kthat knows how to compare itself (even ifcompareTowas inherited from a superclassS, henceComparable<? super K>):static <K extends Comparable<? super K>> List<K> topKeys(Map<K, Long> totals, int k) { if (k < 0) { throw new IllegalArgumentException("k must be >= 0, got " + k); } if (k == 0 || totals.isEmpty()) { return List.of(); } List<K> keys = new ArrayList<>(totals.keySet()); keys.sort(Comparator.comparingLong((K key) -> totals.get(key)).reversed() .thenComparing(Comparator.naturalOrder())); return new ArrayList<>(keys.subList(0, Math.min(k, keys.size()))); }Exceptions: checked vs. unchecked and invalid-input policy
Java divides
Throwableinto three branches: - Checked exceptions (Exceptionsubclasses excludingRuntimeException, such asIOExceptionorSQLException): compiler-enforced contracts for recoverable external conditions (missing file, dropped network socket) that even bug-free callers must handle. - Unchecked runtime exceptions (RuntimeExceptionsubclasses likeIllegalArgumentException,NullPointerException,IllegalStateException): programming errors or violated API preconditions (k < 0,nullmap). - JVMErrors (OutOfMemoryError,StackOverflowError): unrecoverable runtime failures that application code should almost never catch.Error-handling design rules: 1. Ask the interviewer for the bad-record policy: in a strict internal RPC call, fail fast on the first bad record; in a 100-million-line nightly batch feed, skip, record with line numbers, and alert/abort only if the error rate crosses a threshold (dead-letter pattern). 2. Preserve context and causes: include the offending line number and raw input in the message, pass
Throwable causetosuper(msg, cause)so root stack traces survive, and close streams automatically viatry-with-resources. 3. Keep exceptions out of normal control flow: constructing an exception walks the call stack (fillInStackTrace()), which turns hot loops into bottlenecks if millions of lines fail.import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; public class InvalidRecordException extends RuntimeException { private final int lineNumber; public InvalidRecordException(int lineNumber, String message) { super("line " + lineNumber + ": " + message); this.lineNumber = lineNumber; } public InvalidRecordException(int lineNumber, String message, Throwable cause) { super("line " + lineNumber + ": " + message, cause); this.lineNumber = lineNumber; } public int lineNumber() { return lineNumber; } } // IOException is checked (missing/unreadable file); InvalidRecordException is handled per row. class BatchSettlementReader { static Map<String, Long> totalsFromFile(Path csvPath, List<String> rejectedLines) throws IOException { Objects.requireNonNull(csvPath, "csvPath"); Objects.requireNonNull(rejectedLines, "rejectedLines"); Map<String, Long> totals = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(csvPath)) { String line; int lineNo = 0; while ((line = reader.readLine()) != null) { lineNo++; try { Settlement s = TopMerchants.parseLine(line, lineNo); totals.merge(s.merchant(), s.amountCents(), Math::addExact); } catch (InvalidRecordException e) { rejectedLines.add(e.getMessage()); } } } return totals; } }Notice that
ArithmeticExceptionfromMath::addExactis deliberately not caught inside the per-linecatch: overflowing a 64-bitlongbalance is a systemic data/domain error, not a single row typo.Unit testing with JUnit 5: boundaries, regressions, and oracle checks
Write the test for a new requirement before changing production code — seeing it fail first proves the test actually guards against regressions. Organize your JUnit 5 suite systematically:
- Happy path & tie-breaking regression: verifies highest total wins and equal totals sort alphabetically by merchant ID.
- Boundary cases: empty map,
k = 0,k > distinct merchants, single merchant, negative chargeback amounts, andLong.MAX_VALUE + 1balance overflow. - Parameterized malformed-input checks:
@ParameterizedTestexercises every bad CSV shape in one clean method while asserting the exactlineNumber(). - Seeded randomized cross-check (oracle test): generates hundreds of small random inputs with a fixed
new Random(42)seed and assertstopKWithHeapmatches the simpler full-sorttopKword for word — catching subtle heap comparator inversions (reversed()) immediately.
import static org.junit.jupiter.api.Assertions.*; import java.util.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class TopMerchantsTest { @Test void breaksTiesAlphabeticallyByMerchantId() { Map<String, Long> totals = Map.of("m_beta", 750L, "m_alpha", 750L, "m_gamma", 1200L); List<MerchantTotal> expected = List.of( new MerchantTotal("m_gamma", 1200L), new MerchantTotal("m_alpha", 750L) ); assertEquals(expected, TopMerchants.topK(totals, 2)); assertEquals(expected, TopMerchants.topKWithHeap(totals, 2)); } @Test void handlesZeroAndOversizedKBoundaries() { assertEquals(List.of(), TopMerchants.topKWithHeap(Map.of("m_alpha", 100L), 0)); assertEquals(1, TopMerchants.topKWithHeap(Map.of("m_alpha", 100L), 5).size()); assertThrows(IllegalArgumentException.class, () -> TopMerchants.topK(Map.of(), -1)); } @Test void parsesExactDecimalDollarsAndNegativeChargebacks() { assertEquals(new Settlement("m_alpha", 750L), TopMerchants.parseLine("m_alpha, 7.50", 1)); assertEquals(new Settlement("m_alpha", -400L), TopMerchants.parseLine("m_alpha,-4", 2)); } @ParameterizedTest @ValueSource(strings = {"", " ", "m_alpha", "m_alpha,", ",5.00", "m_alpha,abc", "m_alpha,1.005", "m,1,2"}) void rejectsMalformedCsvLinesWithExactLineNumber(String badLine) { InvalidRecordException ex = assertThrows( InvalidRecordException.class, () -> TopMerchants.parseLine(badLine, 9) ); assertEquals(9, ex.lineNumber()); } @Test void detectsLongBalanceOverflow() { List<Settlement> batch = List.of(new Settlement("m_alpha", Long.MAX_VALUE), new Settlement("m_alpha", 1L)); assertThrows(ArithmeticException.class, () -> TopMerchants.aggregateTotals(batch)); } @Test void heapMatchesFullSortAcrossSeededRandomInputs() { Random rng = new Random(42L); for (int trial = 0; trial < 100; trial++) { Map<String, Long> totals = new HashMap<>(); for (int i = 0; i < 30; i++) { // Small value range forces frequent balance ties to stress tie-breaking! totals.put("merch" + rng.nextInt(15), (long) (rng.nextInt(7) - 3) * 100L); } int k = rng.nextInt(10); assertEquals(TopMerchants.topK(totals, k), TopMerchants.topKWithHeap(totals, k)); } } }
Intuition & how it works
Think of your initial coding solution as a temporary wooden footbridge built across a stream, and the Java follow-up round as a civil engineer asking what happens when heavy freight trucks (10^8 rows), storms (corrupt inputs), and wider lanes (new input/output formats) arrive. Instead of treating the six prompts as disconnected textbook trivia, anchor every answer onto one concrete problem — such as finding the top k merchants by net settlement balance — so you can point directly to which line breaks, how many bytes each object uses, and which test proves your fix works.
Candidates often stumble in two opposite ways: either they recite generic textbook definitions of HashMap and checked exceptions without noticing bugs sitting right in their own code (such as List.subList pinning memory or HashMap ties changing order), or they panic at a requirement change and rewrite their working function from scratch in one untested edit. Interviewers ask follow-ups specifically to see whether you evolve working code safely in small pure stages, reason about real JVM object memory beyond bare Big-O notation, and enforce crisp type and error boundaries.
Trace feeding 4 CSV lines — ["m_beta,7.50", "m_alpha,7.50", "corrupt_row", "m_gamma,12.00"] with k = 2 — through the refactored Java pipeline:
- Parse & validate (
parseLine):"m_beta,7.50"and"m_alpha,7.50"convert cleanly viaBigDecimalinto immutablerecordsSettlement("m_beta", 750L)andSettlement("m_alpha", 750L); line 3 ("corrupt_row") throwsInvalidRecordException(line 3), which the batch reader records inrejectedLineswithout crashing the job; line 4 yieldsSettlement("m_gamma", 1200L). - Aggregate (
aggregateTotals):HashMap.mergesums balances into{m_beta=750, m_alpha=750, m_gamma=1200}usingMath::addExactsolongoverflow throwsArithmeticExceptioninstead of silently wrapping negative. - Rank (
topKWithHeap): a bounded size-2PriorityQueueordered worst-first keeps the strongest two merchants; between tied"m_alpha"(750) and"m_beta"(750), alphabetical tie-breaking ranks"m_alpha"ahead of"m_beta", evicting"m_beta"and returning a fresh list[MerchantTotal("m_gamma", 1200), MerchantTotal("m_alpha", 750)].
Key points
- Incremental refactoring: clarify edge-case rules first, lock down existing behavior with baseline tests, split monolithic loops into pure parse -> aggregate -> rank functions, use immutable
records and exactlongcents, and copysubListslices into a newArrayListso large backing lists can be garbage-collected. - Large-data JVM math: on 64-bit HotSpot (where every heap object has a 12-byte object header and 8-byte alignment),
HashMap<String, Long>costs roughly 120 bytes per distinct merchant (~120 MBfor10^6merchants) due toHashMap.Node(32 B), autoboxedLong(24 B),String(56 B), and table slots (~8 B), versus 8 MB for a denselong[]. Stream files withBufferedReader, use a size-kmin-heap (O(m log k)), hash-partition to disk whenmexceeds heap RAM, and profile with JFR and JMH before micro-tuning. - Collections matched to operations: pick
ArrayListfor indexed sequences,ArrayDequefor stacks and queues (faster thanLinkedListand legacysynchronizedStack),HashMapforO(1)average lookup,LinkedHashMapfor insertion/LRU order,TreeMapforO(log n)sorted ranges,PriorityQueuefor streaming top-k, andConcurrentHashMapfor multi-threaded aggregation. - Generics, erasure, and PECS: type erasure strips
<T>type parameters after compile-time checking (disallowingnew T[],instanceof List<String>, and primitiveList<int>). Because generics are invariant (List<Integer>is not aList<Number>), use? extends Tto read from a producer and? super Tto write into a consumer (PECS). - Exceptions and testing: use unchecked
RuntimeExceptions (IllegalArgumentException) for broken caller preconditions and checked exceptions (IOException) for recoverable environmental failures; close streams viatry-with-resources, ask whether corrupt batch records should fail fast or log-and-skip, and test boundaries (k = 0, overflow, ties, malformed lines) plus a seeded random oracle check in JUnit 5.
Common mistakes
- Throwing away working code on a change request: rewriting everything at once discards already-verified behavior instead of extracting small, testable stages.
- Quoting Big-O while ignoring JVM object overhead: assuming
10^6String -> Longentries take16 MBoverlooks object headers,HashMap.Nodewrappers, and autoboxing (~120 MBin practice). - Using
doublefor money or 32-bitintfor cumulative cents:0.1 + 0.2produces0.30000000000000004in binary floating point, andintcents overflow above$21.47M. - Falling into classic Java collection traps: mutating fields of an active
HashMapkey, comparing boxedIntegers with==(fails outside-128..127), writing(a, b) -> a - bcomparators that overflow, or callingList<Integer>.remove(1)expecting value removal instead of index removal. - Swallowing exceptions or losing root causes: catching bare
Exceptionsilently, or throwing a wrapper exception without passingcause, destroys the stack trace needed to debug production incidents. - Testing only happy-path examples: skipping
k = 0(note thatnew PriorityQueue<>(0, comp)throwsIllegalArgumentExceptionin Java!), ties, negative amounts, and malformed inputs.
Follow-up questions
- How can you parallelize aggregation across multiple CPU cores without data races? Sharing a plain
HashMapacross threads is unsafe because concurrentput/resize operations can lose updates or corrupt bucket chains. You can share aConcurrentHashMapusing atomicmerge(merchant, cents, Math::addExact)(orLongAddervalues when a handful of hot merchants receive millions of writes per second), or — usually fastest for batch data — give each worker thread its own uncontended thread-localHashMapover a distinct chunk of lines and merge the per-thread maps once at the end. Always benchmark I/O first, because adding parser threads yields zero speedup if a single disk or network stream is already saturated. - When should monetary values use
longminor units versusBigDecimal, and why isdoubleunsafe?doubleuses IEEE-754 binary floating-point fractions, which cannot represent base-10 decimals like0.10exactly and accumulate rounding drift across thousands of additions. Exactlongcents perform single-instruction CPU integer math with zero heap allocation (up to±$92 quadrillionbefore overflow, guarded byMath.addExact), whereasBigDecimal(arbitrary-precision decimal arithmetic) is necessary when mixing variable decimal scales (such as 4-decimal FX conversion rates) at the cost of heap allocations and slower math — and remember to compareBigDecimalvalues withcompareTorather thanequals, becausenew BigDecimal("1.0").equals(new BigDecimal("1.00"))returnsfalsedue to differing scale! - What invariants must a custom key type satisfy when stored in a
HashMapversus aTreeMap? ForHashMap, equal objects (a.equals(b) == true) must return identicalhashCode()integers, and every field participating inequals/hashCodemust remain immutable while the key sits in the map so lookups search the same bucket where the key was inserted. ForTreeMap, keys must provide a strict weak ordering viaComparableor an explicitComparator(reflexive, antisymmetric, transitive), and that ordering should agree withequals(compare(a, b) == 0if and only ifa.equals(b)), becauseTreeMaptreats any two keys returning0as duplicates and overwrites the value. Declaring keys as immutable Javarecords automatically synthesizes consistentequalsandhashCodeimplementations across all fields.
Follow-up questions
- How can you parallelize aggregation across multiple CPU cores without data races?
- When should monetary values use `long` minor units versus `BigDecimal`, and why is `double` unsafe?
- What invariants must a custom key type satisfy when stored in a `HashMap` versus a `TreeMap`?
Similar questions
- Combined Behavioral and Practical Software Engineering Deep Dive
- Binary Tree Equality and Bracket Validation
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging