Incremental TDD Pair Session: Building a Java Set
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
You are participating in a navigator-driver Test-Driven Development (TDD) pairing round where you speak through every decision while the interviewer writes the Java and JUnit code at the keyboard. Together, you incrementally construct a custom Set class from an empty file—one unit test and one minimal production edit at a time.
Throughout the coding portion, asymptotic time and memory efficiency are intentionally out of scope. Instead, the interviewer evaluates whether every line of production code is strictly forced by a failing unit test and represents the bare minimum needed to turn the suite green (for example, isEmpty() requires zero element storage until later tests demand remembering inserted items). Because your partner types, clear verbal direction, behavioral test naming, and calm joint debugging matter just as much as the code itself.
Clarify any open contract details up front (such as core operations like isEmpty(), add(x), contains(x), remove(x), and size(), return values, starting element type, null behavior, .equals() vs. ==, and whether basic list delegation is permitted), then walk through three stages:
- Test design and ordering: Sequence the operations and individual JUnit cases—covering positive behaviors, negative checks, edge cases, and cross-operation interactions—so each new test fails for a single, predictable reason.
- Minimal Red-Green-Refactor execution: Direct the step-by-step code changes from an empty class, explaining why each change is minimal, when earlier shortcuts become obsolete, how to refactor safely while green, and how to diagnose unexpected test failures together.
- Future evolution (verbal discussion): Without writing additional code, explain how you would extend the API, introduce generic element types with clear equality/hashing contracts, and upgrade internal storage for large-scale performance while relying on your existing test suite.
Scope & Expectations
- Clarify open API rules first and order small, descriptive JUnit tests from least state required to most state required, including duplicates, absent removals, and value equality.
- Apply strict Red-Green-Refactor discipline at every step—starting from constants and single fields before introducing a collection, and removing redundant state while green.
- Communicate crisp, unambiguous instructions to the driver and demonstrate hypothesis-driven collaborative debugging when a test fails.
- Articulate how to scale the class later with richer set operations, generics,
equals/hashCodeinvariants, andO(1)hash-based storage without rewriting behavioral tests.
Step-by-step walkthrough
Clarify the API and agree on the TDD loop
Because you are navigating verbally while the interviewer types, spend the first two minutes pinning down the open rules. Every answer you agree on becomes a concrete unit test later:
- Minimal set API: Start with
isEmpty(),add(x),contains(x),remove(x), andsize(). Keepvoid addandvoid removeat first; returning abooleanflag when membership changes can be added later if time permits. - Element type: Start with
Stringrather than generics (SimpleSet<T>) so the first tests need minimal boilerplate. nullpolicy: Disallownullelements —add(null)throwsNullPointerException, whilecontains(null)returnsfalse.- Equality rule: Two elements count as the same when
a.equals(b)istrue(value equality), not only whena == b(reference identity, meaning the exact same object in memory). - Backing storage: Delegating to
java.util.ArrayListis allowed once multiple elements must be stored, since runtime complexity is explicitly out of scope during coding.
State the Red-Green-Refactor loop (the three-phase cycle of Test-Driven Development, or TDD) out loud so your partner knows what to expect at every turn:
1. RED Dictate ONE small JUnit test, predict how it will fail, and run it. 2. GREEN Dictate the smallest, simplest code change that turns all tests green. 3. REFACTOR While all tests are green, remove duplicated state or outgrown shortcuts, then re-run.Dictate clearly enough that your partner never has to guess variable or method names — for example: "In
SimpleSetTest, add@Test void setContainsAddedElement(). CreateSimpleSet set = new SimpleSet(), callset.add("apple"), and callassertTrue(set.contains("apple"))."- Minimal set API: Start with
Part 1: Order operations and unit tests so each forces one change
Order the operations from least state required to most state required (
isEmpty->add->contains->size->remove-> contracts), and sequence the unit tests (small, isolated automated checks of one behavior) so each new test fails for one exact reason:Test # Descriptive JUnit method name Smallest state / logic forced ------ ---------------------------------------------- ------------------------------------------- 1 newSetIsEmpty SimpleSet class; isEmpty() returns true 2 setIsNotEmptyAfterAdd add(x) + single `boolean empty = true` 3 newSetContainsNothing contains(x) returns false 4 setContainsAddedElement contains(x) returns !empty 5 setDoesNotContainElementThatWasNeverAdded remember 1 item: `String singleElement` 6 setContainsEveryAddedElement remember N items: `List<String> elements` -> [Refactor while green: derive isEmpty() from elements.isEmpty(); delete `boolean empty`] 7 newSetHasSizeZero size() returns 0 8 sizeCountsDistinctAddedElements size() returns elements.size() 9 addingDuplicateDoesNotIncreaseSize if (!elements.contains(x)) before adding 10 removedElementIsNoLongerContained remove(x) calls elements.remove(x) 11 setIsEmptyAfterRemovingOnlyElement catches stale-boolean bug if not refactored 12 removingOneElementKeepsOtherElements interaction: remove + contains on survivors 13 removingAbsentElementLeavesSetUnchanged negative case on remove 14 duplicateAddedElementIsGoneAfterSingleRemove interaction: duplicate add + single remove 15 containsComparesByEqualsNotReferenceIdentity value equality contract (distinct objects) 16 addingNullThrowsNullPointerException null policy + set stays unchangedNotice how every operation gets positive cases, negative cases (empty set, absent item), and interaction cases (how
addduplicates affectsizeandremove, and howremoveaffectsisEmpty).Part 2a: Grow `isEmpty` and `add` from a constant to one boolean
Test 1 (
newSetIsEmpty): - Red: Does not compile yet becauseSimpleSetandisEmpty()do not exist.@Test void newSetIsEmpty() { SimpleSet set = new SimpleSet(); assertTrue(set.isEmpty()); }- Green: Hard-code
return true;. Nothing in the test suite has added an element yet, so any field or list would be speculative code.
public class SimpleSet { public boolean isEmpty() { return true; } }Test 2 (
setIsNotEmptyAfterAdd): Callset.add("apple"), thenassertFalse(set.isEmpty()). - Red: Fails becauseisEmpty()still returnstrue. - Green: Addprivate boolean empty = true;and setempty = false;insideadd. Do not store"apple"yet — no test asks what was added! Tell the interviewer out loud: "I knowemptycannot becometrueagain onceremoveexists; a later interaction test will force us to replace it."public class SimpleSet { private boolean empty = true; public boolean isEmpty() { return empty; } public void add(String element) { empty = false; } }- Green: Hard-code
Part 2b: Grow `contains` from zero, to one field, to a list
Here we follow the classic TDD "0 -> 1 -> many" progression:
- Test 3 (
newSetContainsNothing):assertFalse(new SimpleSet().contains("apple")).- Green: Add
public boolean contains(String candidate) { return false; }.
- Green: Add
- Test 4 (
setContainsAddedElement):set.add("apple"); assertTrue(set.contains("apple"));.- Green: Change
containstoreturn !empty;. Because no test queries a different string yet, reusing the boolean is genuinely the simplest passing change.
- Green: Change
- Test 5 (
setDoesNotContainElementThatWasNeverAdded):set.add("apple"); assertFalse(set.contains("pear"));.- Red:
!emptywrongly returnstruefor"pear". - Green: Store one
String singleElementfield. Checkthis.singleElement != nullbefore calling.equals(candidate)so callingcontainson an empty set (or withnull) never throwsNullPointerException:
- Red:
public class SimpleSet { private boolean empty = true; private String singleElement; public boolean isEmpty() { return empty; } public void add(String element) { empty = false; this.singleElement = element; } public boolean contains(String candidate) { return this.singleElement != null && this.singleElement.equals(candidate); } }- Test 6 (
setContainsEveryAddedElement): Add"apple"and"pear", then assert bothcontains("apple")andcontains("pear")aretrue.- Red:
singleElementoverwrites"apple"with"pear", socontains("apple")fails. - Refactor-first option (while green): If the interviewer asks you to refactor while tests are green before adding behavior, mark Test 6
@Disabledtemporarily. ReplacesingleElementwithList<String> elements = new ArrayList<>()whereaddrunselements.clear(); elements.add(element);— Tests 1–5 stay green because behavior is unchanged. Then re-enable Test 6 and deleteelements.clear();(a tiny one-line change) to turn Test 6 green! - Refactor out duplicated state immediately: Once Test 6 passes, both
boolean emptyandelementstrack emptiness. Having two sources of truth invites bugs. While all 6 tests are green, changeisEmpty()toreturn elements.isEmpty();, deleteprivate boolean empty, and re-run all 6 tests.
- Red:
- Test 3 (
Part 2c: Add `size`, reject duplicates, and implement `remove`
Now each remaining core operation takes tiny, clean steps:
- Test 7 (
newSetHasSizeZero):assertEquals(0, new SimpleSet().size())-> Green:return 0;. - Test 8 (
sizeCountsDistinctAddedElements): Add"apple"and"pear", expect2-> Green:return elements.size();. - Test 9 (
addingDuplicateDoesNotIncreaseSize): Callset.add("apple")twice, expectsize() == 1.- Red:
ArrayList.addappends blindly, failing withexpected: <1> but was: <2>. - Green: Guard
addwithif (!elements.contains(element)).
- Red:
- Test 10 (
removedElementIsNoLongerContained): Add"apple", callset.remove("apple"), assert!set.contains("apple")-> Green:elements.remove(element);. - Tests 11–14 (
setIsEmptyAfterRemovingOnlyElement,removingOneElementKeepsOtherElements,removingAbsentElementLeavesSetUnchanged,duplicateAddedElementIsGoneAfterSingleRemove):- Because we refactored
isEmpty()to delegate toelements.isEmpty()and prevented duplicate entries inadd(), Tests 11–14 pass right away. - Verify each immediately-green test can fail: Whenever a new test passes on the first run, ask the interviewer to temporarily comment out
elements.remove(element)(orif (!elements.contains(element))), watch the test turn red for the expected reason, and restore the line. That proves the test is not vacuously green.
- Because we refactored
- Test 7 (
Part 2d: Test value equality, null rejection, and collaborative debugging
Test 15 (
containsComparesByEqualsNotReferenceIdentity): In Java, string interning causes two identical string literals"apple"and"apple"in source code to point to the exact sameStringobject in memory, so a buggy==check would accidentally pass! Construct two distinct objects and prove they are distinct withassertNotSame:@Test void containsComparesByEqualsNotReferenceIdentity() { String stored = new String("apple"); String probe = new String("apple"); assertNotSame(stored, probe); SimpleSet set = new SimpleSet(); set.add(stored); assertTrue(set.contains(probe)); }How to debug together if Test 15 fails: Suppose earlier at Test 6 you had written a manual loop
for (String item : elements) { if (item == candidate) return true; }. Tests 1–14 would all pass (thanks to string interning), and Test 15 would fail withexpected: <true> but was: <false>. Walk through your debugging thought process out loud: 1. Read the assertion failure (contains(probe)returnedfalse). 2. State a hypothesis: "Our loop compares object references with==instead of value equality with.equals()." 3. VerifyassertNotSame(stored, probe)succeeded above, confirming two separateStringinstances were used. 4. Apply the minimal fix (item.equals(candidate), or delegate toelements.contains(candidate)which usesequals), then run the full suite.Test 16 (
addingNullThrowsNullPointerException): AssertassertThrows(NullPointerException.class, () -> set.add(null))andassertTrue(set.isEmpty())-> Green: addObjects.requireNonNull(element, "element must not be null");at the top ofadd. Here is the finishedSimpleSet:import java.util.ArrayList; import java.util.List; import java.util.Objects; public class SimpleSet { private final List<String> elements = new ArrayList<>(); public boolean isEmpty() { return elements.isEmpty(); } public void add(String element) { Objects.requireNonNull(element, "element must not be null"); if (!elements.contains(element)) { elements.add(element); } } public boolean contains(String element) { return elements.contains(element); } public void remove(String element) { elements.remove(element); } public int size() { return elements.size(); } }Part 3: Expand the set with richer operations, O(1) hashing, and generics
When coding stops, clarify whether "expand" means more operations, scaling to large input sizes, or type generality, and address all three concisely:
- Additional operations (and the tests driving each):
- Boolean return values on
add/remove:addReturnsTrueWhenNewElementAdded,addReturnsFalseWhenDuplicateAdded,removeReturnsFalseWhenElementAbsent. - Iteration (
Iterable<T>):iteratorVisitsEveryElementExactlyOnce— collect yielded items into aList, checklist.size() == set.size(), and compare sorted copies (never assert a fixed iteration order, since sets are unordered). - Set algebra:
union,intersection, anddifferencetested on disjoint sets, overlapping sets ({a, b}and{b, c}-> union size3, intersection{b}), empty sets, andset.union(set).
- Boolean return values on
- Scaling storage from
O(n)toO(1)average time:- Right now
elements.contains(x)scans the list linearly (O(n)). Insertingn = 100,000distinct elements performs0 + 1 + 2 + ... + 99,999 = n(n - 1) / 2 ≈ 5 × 10^9(5 billion)equalscomparisons! - Replacing
ArrayListwith a hash table (an array of buckets indexed byelement.hashCode(), givingO(1)averageadd/contains/remove, or a balanced binary search tree forO(log n)sorted order) drops100,000inserts to roughly100,000bucket lookups. - Because Tests 1–16 only call public methods (
isEmpty,add,contains,remove,size), every existing test stays 100% unchanged as a regression safety net! Add new storage-stress tests: inserting10,000elements across table resizes, and inserting distinct objects with a constanthashCode()(return 42;) to verify hash collision handling.
- Right now
- Generics and element contracts (
SimpleSet<T>):- Parameterize
SimpleSet<T>(noting a classic Java overload trap: onList<Integer>,list.remove(5)removes index 5, whereaslist.remove((Object) element)removes the value). - Document two required contracts on
T: (1) ifa.equals(b)istrue, thena.hashCode() == b.hashCode()must hold, and (2) elements must not be mutated in a way that changesequals/hashCodewhile stored in the set.
- Parameterize
- Additional operations (and the tests driving each):
Intuition & how it works
Think of Test-Driven Development (TDD) (a workflow where you write a failing automated test before writing any production code) like climbing a rock face using safety pitons: before you reach up for the next handhold, you clip in one small safety pin (RED: write one small unit test, an isolated automated check of a single behavior, and watch it fail), make the smallest movement that reaches that pin (GREEN: write the simplest possible code that passes), and tidy your footing while clipped in safely (REFACTOR: clean up duplication without changing behavior while all tests pass). In a pair-programming format where the interviewer types your instructions, this tiny step size proves two skills at once: disciplined incremental design and crystal-clear verbal communication.
The naive instinct in interviews is to immediately dictate a full HashSet with a bucket array, resizing math, generics, and a size counter before running a single test. That approach fails this exercise's core evaluation criteria because you write dozens of untested lines at once, introduce multiple bugs simultaneously when a test finally runs, and violate the core rule of writing only the minimal logic demanded by the active failing test.
Walk through how the first 6 tests grow SimpleSet from zero state to a list one forced change at a time:
newSetIsEmptyfails because the class does not exist -> return the constanttruefromisEmpty()(0 fields).setIsNotEmptyAfterAddcallsadd("apple")and expectsisEmpty() == false-> add a singleboolean empty = trueflipped tofalseinsideadd(still 0 elements stored).newSetContainsNothingandsetContainsAddedElementask whether"apple"is present ->containsreturnsfalse, then!empty.setDoesNotContainElementThatWasNeverAddedadds"apple"and checkscontains("pear") == false->!emptyfails, forcing a singleString singleElementfield.setContainsEveryAddedElementadds both"apple"and"pear"->singleElementoverwrites"apple", forcing aList<String> elements = new ArrayList<>(), immediately followed by a green refactor replacingreturn empty;withreturn elements.isEmpty();and deletingboolean empty.
Key points
- Sequence tests from least state to most state: Start with
isEmpty(), thenadd,contains,size,remove, and finally value-equality andnullcontracts so every red test fails for exactly one predictable reason. - Take deliberate shortcuts and name their future breaking test: Using
boolean emptyorString singleElementon purpose — while stating out loud which upcoming test will break it — shows the interviewer your small steps are intentional discipline, not oversight. - Eliminate duplicated state during Refactor: As soon as
List<String> elementsis introduced, deleteboolean emptyand computeisEmpty()fromelements.isEmpty()while tests are green so the two can never drift out of sync. - Cover positive, negative, and interaction cases: Test not just happy paths, but absent elements (
contains("pear")), duplicateadd("apple")calls (size() == 1), and cross-method interactions (addthenremove->isEmpty()istrueagain; twoadds then oneremove-> element is gone). - Test public behavior, never internal storage: Tests written strictly against public methods (
isEmpty,add,contains,remove,size) survive swappingArrayList(O(n)lookup) for a hash table (an array of buckets indexed byhashCode()forO(1)average lookup) with zero test edits. - Verify immediately-passing tests can fail: When an interaction test passes on the first try, briefly break the production line it guards, watch the test turn red, and undo the break so you know the test actually checks what its name claims.
Common mistakes
- Building a full data structure upfront: Jumping straight to
ArrayListorHashMapon Test 1 violates minimal test-driven incrementalism before any test requires element storage. - Writing a batch of 5 tests before writing code: Having multiple red tests at once hides which change fixed what and turns small steps into guesswork.
- Skipping negative tests: Without
setDoesNotContainElementThatWasNeverAdded,contains(x) { return !empty; }passes every positivecontainstest forever. - Testing
equalswith Java string literals: Because string interning (Java's reuse of a singleStringinstance in memory for identical source literals like"apple") makes"apple" == "apple"true, a test using literals passes even when production code wrongly uses==; always usenew String("apple")plusassertNotSame. - Keeping both
boolean emptyandList<String> elements: Leaving redundant state behind causesisEmpty()to stayfalseforever after the last element is removed. - Asserting iteration order or
toString()format: Sets are unordered; asserting list insertion order makes tests brittle and causes false failures when switching to a hash table.
Follow-up questions
- After introducing
remove(x), why does a standalonebooleanflag forisEmpty()break down, which specific unit test exposes the defect, and what habit ensures you never miss that test?addflipsempty = false, andremovecannot safely flipempty = truewithout knowing whether other elements still remain in the set. The test that exposes this bug issetIsEmptyAfterRemovingOnlyElement(add("apple"),remove("apple"), thenassertTrue(set.isEmpty()), paired withremovingOneElementKeepsOtherElementswhereisEmpty()must stayfalse). You guarantee this test gets written by following a systematic checklist: whenever you introduce a mutating method (addorremove), write an interaction test checking its effect on every existing query method (isEmpty,contains,size), and delete redundant state (boolean empty) during refactoring as soon aselementsexists. - Suppose you replace the internal list with bucketed hash storage to reach O(1) lookups. How many of your prior unit tests should require edits, and why? Zero existing tests should require edits, because every unit test only exercises the public set contract (
isEmpty,add,contains,remove,size) rather than inspecting the internalArrayListor assuming insertion order. Any test that broke during the switch was either over-specified (for instance, asserting a specific iteration order) or used a custom test class that overrodeequalswithout overridinghashCode(violating Java's rule that equal objects must produce identical hash codes so they land in the same hash bucket). - What JUnit test proves your collection checks value equality (
.equals()) instead of object reference identity (==) in Java? Create two separate objects in memory with equal values — such asString stored = new String("apple")andString probe = new String("apple")(or two instances of a custom value record) — and first callassertNotSame(stored, probe)to provestored != probe. Then callset.add(stored)andassertTrue(set.contains(probe))(plusset.remove(probe)followed byassertTrue(set.isEmpty())), which fails immediately if the implementation uses==instead of.equals(). - What happens to
contains(x)if a caller mutates an already-inserted object so its equality and hash code change, and what contract should the class specify? Just likejava.util.Set, a set's behavior when a stored element mutates itsequals/hashCodestate should be documented as undefined / forbidden by contract, and callers should use immutable element types (String,Integer, Javarecords). In ourArrayList-backed implementation,containsscans linearly on every call, socontains(newValue)returnstrueandcontains(oldValue)returnsfalse— though mutating one element to equal an already-stored element silently creates a duplicate in the list and breakssize()andremove(). In a hash-table-backed set, the mutated object remains stuck in the bucket computed from its oldhashCode(), socontains(newValue)looks in the wrong bucket (false) andcontains(oldValue)finds the bucket but failsequals()(false), making the element an unreachable "ghost" entry.
Follow-up questions
- After introducing `remove(x)`, why does a standalone `boolean` flag for `isEmpty()` break down, which specific unit test exposes the defect, and what habit ensures you never miss that test?
- Suppose you replace the internal list with bucketed hash storage to reach O(1) lookups. How many of your prior unit tests should require edits, and why?
- What JUnit test proves your collection checks value equality (`.equals()`) instead of object reference identity (`==`) in Java?
- What happens to `contains(x)` if a caller mutates an already-inserted object so its equality and hash code change, and what contract should the class specify?
Similar questions
- Building a Multiset Incrementally with TDD
- 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
- Library Hold-Queue and Loan Reminder Notification Manager