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:

  1. 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.
  2. 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.
  3. 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.
  4. Parameterized types (generics): How generics operate under the hood in Java, including type erasure, invariance, bounded wildcards (extends / super), and design trade-offs.
  5. Error and exception modeling: Distinguishing checked from unchecked exceptions, following clean throw/catch practices, and handling malformed or out-of-range inputs safely.
  6. 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

  1. 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 the k merchants 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 HashMap bucket 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 raw ArrayIndexOutOfBoundsException; worse, if amounts.length > merchants.length, extra settlements are silently ignored. Passing k < 0 throws an IllegalArgumentException deep inside subList with an unhelpful message.
    • List.subList view retention: keys.subList(0, k) returns a live view backed by the entire keys list rather than an independent copy — returning 10 winners prevents garbage-collecting a 1,000,000-element backing list, and mutating keys later triggers ConcurrentModificationException.
    • Autoboxing and object churn: autoboxing (Java automatically wrapping a primitive long inside a heap-allocated java.lang.Long object) allocates new Long wrappers on updates outside the tiny -128..127 cache, plus one HashMap.Node object per distinct merchant.
  2. 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:

    1. 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?
    2. Pin existing behavior with tests before editing so refactoring cannot silently break working logic.
    3. 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, only parseLine changes.
    4. Encode invariants in types: replace parallel arrays with Java records (compact immutable data classes that automatically generate equals, hashCode, and toString), and keep money in exact long cents (double binary floating point cannot represent 0.10 exactly, and 32-bit int cents overflow at 2,147,483,647 cents ≈ $21.47M).
    5. Preserve backward compatibility if callers already exist by keeping the old signature as a thin @Deprecated wrapper 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())));
        }
    }
    
  3. Scaling to large datasets on the JVM

    Quantify scale with concrete numbers: suppose we process n = 10^8 CSV lines (~2.5 GB) spanning m = 10^6 distinct merchants, with k = 10.

    • Time complexity: streaming and aggregating into HashMap takes O(n) average time. Sorting all m merchants takes O(m log m) (~10^6 × 20 ≈ 2 × 10^7 comparisons, under 0.2 seconds), while maintaining a bounded size-k min-heap takes O(m log k) (~10^6 × 3.3 operations) and avoids allocating an m-element ArrayList. 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:

    1. Stream line by line: read with Files.newBufferedReader(path) so only one line lives in young-generation RAM at a time; Files.readAllLines would materialize 10^8 Strings (> 5.6 GB) and crash with OutOfMemoryError.
    2. Eliminate boxing and node wrappers: if merchant IDs map to dense integers ("MERCH00042" -> 42), accumulate into a flat long[] (8 MB, zero GC churn). For arbitrary string IDs, an open-addressed primitive map (like FastUtil's Object2LongOpenHashMap) stores keys in a flat Object[] and totals in a parallel long[], cutting Node and Long allocations completely.
    3. Bound ranking memory to O(k) with a min-heap: keep only the strongest k merchants in a PriorityQueue ordered worst-first so the weakest top-k candidate sits at peek() 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;
    }
    
    1. Out-of-core partitioning when m exceeds RAM: hash-partition incoming lines into P spill files by Math.floorMod(merchant.hashCode(), P) so every settlement for the same merchant lands in the same file, aggregate each file independently in memory, and merge the P top-k lists. Always measure first with Java Flight Recorder (JFR), GC logs (-Xlog:gc), and JMH (Java Microbenchmark Harness, which accounts for JIT warm-up).
  4. 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 ArrayList get O(1), append amortized O(1), middle remove O(n) Contiguous Object[] gives fast CPU cache locality; default List.
    LIFO stack or FIFO queue ArrayDeque push/pop/offer/poll amortized O(1) Circular array; beats legacy synchronized Stack and node-heavy LinkedList (forbids null).
    Frequent middle splice at a known cursor LinkedList (rare) O(1) via ListIterator, O(n) get(i) Allocates a 24-byte Node per item and scatters pointers in RAM; almost never faster than ArrayList.
    Unordered key -> value lookup HashMap / HashSet O(1) average, O(log n) worst-case bucket (Java 8+ treeify) Hash table; converts collided chains (>= 8 nodes, table >= 64) to red-black trees when keys are Comparable.
    Insertion-ordered map or bounded LRU cache LinkedHashMap O(1) average HashMap + doubly linked list across entries (accessOrder=true + removeEldestEntry builds an LRU cache).
    Sorted keys & range queries TreeMap / TreeSet O(log n) lookup/insert/range Red-black balanced binary search tree supporting floorKey, ceilingKey, and subMap.
    Repeated min / max extraction PriorityQueue offer/poll O(log n), peek O(1) Array-backed binary heap (note: remove(Object) is O(n) linear scan).
    Multi-threaded key aggregation ConcurrentHashMap O(1) average under contention Fine-grained per-bin locking + CAS atomic merge/compute (forbids null keys and values).

    Classic Java collection pitfalls interviewers test: - Mutating a HashMap key after insertion: changing a field used by hashCode() strands the entry in the wrong bucket forever — always use immutable keys (String, record). - Breaking the equals/hashCode contract: overriding equals without hashCode puts equal keys in different hash buckets. - Overload trap List<Integer>.remove(1): calls remove(int index) (deletes element at index 1), whereas remove(Integer.valueOf(1)) deletes the value 1. - Boxed == reference comparison: Integer a = 1000, b = 1000; a == b evaluates to false because Integer.valueOf only caches -128..127 by default — always compare objects with .equals() or unbox to primitives. - Subtraction comparator overflow: (a, b) -> a - b overflows when a = Integer.MIN_VALUE and b = 1; always use Integer.compare(a, b) or Long.compare(a, b). - TreeMap comparator inconsistent with equals: TreeMap decides key equality solely by compare(a, b) == 0, so sorting merchants only by balance in a TreeMap silently overwrites tied merchants!

  5. 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> to Object (or its upper bound like Comparable), 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() is true (both are ArrayList.class). - You cannot write new T(), new T[10], or obj instanceof List<String> (pass a Class<T> token or IntFunction<T[]> array factory when needed), nor can you overload void handle(List<String>) alongside void handle(List<Integer>) (identical erased signature handle(List)). - Type arguments cannot be primitives (List<int> does not compile), forcing boxed List<Integer> overhead.

    Invariance and PECS wildcards (Producer extends, Consumer super): Java generics are invariant: List<Integer> is not a subtype of List<Number> (otherwise someone could add a Double into an Integer list). By contrast, Java arrays are covariant (Object[] arr = new String[1]; arr[0] = 42;), which compiles cleanly and crashes at runtime with ArrayStoreException. To write flexible APIs safely, use bounded wildcards: - ? extends T (Producer): safe to read T values out (you cannot safely add items because the exact subtype is unknown). - ? super T (Consumer): safe to write T values in (used for comparators and output collections).

    Applying PECS generalizes our ranking helper to any key type K that knows how to compare itself (even if compareTo was inherited from a superclass S, hence Comparable<? 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())));
    }
    
  6. Exceptions: checked vs. unchecked and invalid-input policy

    Java divides Throwable into three branches: - Checked exceptions (Exception subclasses excluding RuntimeException, such as IOException or SQLException): compiler-enforced contracts for recoverable external conditions (missing file, dropped network socket) that even bug-free callers must handle. - Unchecked runtime exceptions (RuntimeException subclasses like IllegalArgumentException, NullPointerException, IllegalStateException): programming errors or violated API preconditions (k < 0, null map). - JVM Errors (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 cause to super(msg, cause) so root stack traces survive, and close streams automatically via try-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 ArithmeticException from Math::addExact is deliberately not caught inside the per-line catch: overflowing a 64-bit long balance is a systemic data/domain error, not a single row typo.

  7. 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, and Long.MAX_VALUE + 1 balance overflow.
    • Parameterized malformed-input checks: @ParameterizedTest exercises every bad CSV shape in one clean method while asserting the exact lineNumber().
    • Seeded randomized cross-check (oracle test): generates hundreds of small random inputs with a fixed new Random(42) seed and asserts topKWithHeap matches the simpler full-sort topK word 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:

  1. Parse & validate (parseLine): "m_beta,7.50" and "m_alpha,7.50" convert cleanly via BigDecimal into immutable records Settlement("m_beta", 750L) and Settlement("m_alpha", 750L); line 3 ("corrupt_row") throws InvalidRecordException(line 3), which the batch reader records in rejectedLines without crashing the job; line 4 yields Settlement("m_gamma", 1200L).
  2. Aggregate (aggregateTotals): HashMap.merge sums balances into {m_beta=750, m_alpha=750, m_gamma=1200} using Math::addExact so long overflow throws ArithmeticException instead of silently wrapping negative.
  3. Rank (topKWithHeap): a bounded size-2 PriorityQueue ordered 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 exact long cents, and copy subList slices into a new ArrayList so 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 MB for 10^6 merchants) due to HashMap.Node (32 B), autoboxed Long (24 B), String (56 B), and table slots (~8 B), versus 8 MB for a dense long[]. Stream files with BufferedReader, use a size-k min-heap (O(m log k)), hash-partition to disk when m exceeds heap RAM, and profile with JFR and JMH before micro-tuning.
  • Collections matched to operations: pick ArrayList for indexed sequences, ArrayDeque for stacks and queues (faster than LinkedList and legacy synchronized Stack), HashMap for O(1) average lookup, LinkedHashMap for insertion/LRU order, TreeMap for O(log n) sorted ranges, PriorityQueue for streaming top-k, and ConcurrentHashMap for multi-threaded aggregation.
  • Generics, erasure, and PECS: type erasure strips <T> type parameters after compile-time checking (disallowing new T[], instanceof List<String>, and primitive List<int>). Because generics are invariant (List<Integer> is not a List<Number>), use ? extends T to read from a producer and ? super T to 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 via try-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^6 String -> Long entries take 16 MB overlooks object headers, HashMap.Node wrappers, and autoboxing (~120 MB in practice).
  • Using double for money or 32-bit int for cumulative cents: 0.1 + 0.2 produces 0.30000000000000004 in binary floating point, and int cents overflow above $21.47M.
  • Falling into classic Java collection traps: mutating fields of an active HashMap key, comparing boxed Integers with == (fails outside -128..127), writing (a, b) -> a - b comparators that overflow, or calling List<Integer>.remove(1) expecting value removal instead of index removal.
  • Swallowing exceptions or losing root causes: catching bare Exception silently, or throwing a wrapper exception without passing cause, destroys the stack trace needed to debug production incidents.
  • Testing only happy-path examples: skipping k = 0 (note that new PriorityQueue<>(0, comp) throws IllegalArgumentException in 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 HashMap across threads is unsafe because concurrent put/resize operations can lose updates or corrupt bucket chains. You can share a ConcurrentHashMap using atomic merge(merchant, cents, Math::addExact) (or LongAdder values 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-local HashMap over 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 long minor units versus BigDecimal, and why is double unsafe? double uses IEEE-754 binary floating-point fractions, which cannot represent base-10 decimals like 0.10 exactly and accumulate rounding drift across thousands of additions. Exact long cents perform single-instruction CPU integer math with zero heap allocation (up to ±$92 quadrillion before overflow, guarded by Math.addExact), whereas BigDecimal (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 compare BigDecimal values with compareTo rather than equals, because new BigDecimal("1.0").equals(new BigDecimal("1.00")) returns false due to differing scale!
  • What invariants must a custom key type satisfy when stored in a HashMap versus a TreeMap? For HashMap, equal objects (a.equals(b) == true) must return identical hashCode() integers, and every field participating in equals/hashCode must remain immutable while the key sits in the map so lookups search the same bucket where the key was inserted. For TreeMap, keys must provide a strict weak ordering via Comparable or an explicit Comparator (reflexive, antisymmetric, transitive), and that ordering should agree with equals (compare(a, b) == 0 if and only if a.equals(b)), because TreeMap treats any two keys returning 0 as duplicates and overwrites the value. Declaring keys as immutable Java records automatically synthesizes consistent equals and hashCode implementations across all fields.

Follow-up questions

Similar questions

More Deutsche Bank interview questions

All 3 Deutsche Bank questions →