PP26  ·  Lab 2  ·  part E · reading guide · Java · homework

Four Holes, All Final

java/PQueue.java is 102 lines, and four of its methods are missing — the same four as in Python, in the same order. What has changed is who enforces the discipline: final fields, a record for the node, a final class. This note walks through what each hole is for, what the surrounding code guarantees, and how to recognise a correct result — without supplying the four bodies.

01 — the file

What is given, and what is left to write

Four bodies are missing, ordered so that each may use the one before it. Around them, every keyword from the lecture's “why private and final?” slide is doing its job.

linenamestatuswhat it is
24Node<T>givenThe cons cell, as a record: head and tail, both final by construction, no setters possible.
27Dequeued<T>givenWhat dequeue returns: the value and the new version, in one type.
29front, backgivenTwo final fields. Assigned once, in the constructor, and never again.
32constructorgivenprivate. Nobody outside builds a queue by hand — and inside, only make should.
37EMPTY, empty()givenOne shared empty queue, safe to share precisely because no operation can modify it.
47isEmptygivenChecks front only — legal precisely because of the invariant.
52peekgivenReads front.head(), and shows the exact idiom for refusing the empty queue.
60revTODO 1Reverse a cons-list. private static: it belongs to no particular queue.
67makeTODO 2The smart constructor that restores the invariant. Also private static.
73enqueueTODO 3Add at the back. O(1). An instance method: q.enqueue(x).
79dequeueTODO 4Take from the front; return a Dequeued. Throws on the empty queue.
87toListgivenThe abstraction function. The tests measure the implementation against it.
97of(…)givenConvenience: enqueue everything in a varargs list.

Note the shape of the calls. In Python it was enqueue(q, x); here it is q.enqueue(x), and inside the body the queue is this — its halves are front and back. rev and make are static because they take their lists as arguments and belong to no instance. Both are private: the class is the only place the representation is visible, which is why the invariant only needs keeping here.

02 — the representation

Two lists, spelled out in keywords

The same two lists as before: front oldest-first, back newest-first. null plays the empty list, and a Node is a cell. What Python asked for politely, the declarations here enforce.

java/PQueue.javalines 14–16, 24
private record Node<T>(T head, Node<T> tail) {}
// null is the empty list; new Node<>(h, t) is a cell

contents(front, back)  =  front ++ reverse(back)

invariant:   front == null  ⟹  back == null
A record has accessors and no setters. n.head() and n.tail() read; nothing writes. Combined with the final fields of the queue itself and the final class, there is no path by which an existing version can change — mutation is not merely discouraged, it does not compile.

The only mistake still available is the structural one: rebuilding a list that should have been shared. Tests.java does not inspect the representation, so nothing there catches it; the solver's inspection mode and the benchmark in part D are where it would show.

03 — todo 1

rev(lst) — reverse a cons-list

The only piece of real list work in the file. Everything else is a rearrangement of references.

java/PQueue.javalines 57–62
/** TODO 1: reverse a cons-list, returning a new cons-list.
 *  A plain loop over local variables is fine — the nodes themselves
 *  cannot be modified (records have no setters). */
private static <T> Node<T> rev(Node<T> lst) {
    throw new UnsupportedOperationException("TODO 1: rev");
}

Take the comment's permission seriously. Recursion is not required, and on the large maze it would give a StackOverflowError rather than a path. The shape is the standard accumulator walk: carry a second list that starts at null, and keep moving the head of the input onto the head of the accumulator until the input is exhausted. Each step is one new Node<>(…).

rev(1 → 2 → 3 → null) — trace
stepremaining inputaccumulator
01 → 2 → 3 → nullnull
12 → 3 → null1 → null
23 → null2 → 1 → null
3null3 → 2 → 1 → null

The accumulator is the return value once the input runs out. Note what doesn't happen in that table: no node of the input is ever altered — it could not be. The old list is intact at step 3; a new spine was built alongside it.

Check yourself before moving on

rev(null) must give null, not throw. Reversing twice must give a list whose head()s read the same. rev is private, so no test can reach it directly — the round trip in basics is the first place a wrong rev shows, two TODOs later.

04 — todo 2

make(front, back) — the smart constructor

The heart of the data structure, and the only place — besides EMPTY — where new PQueue<>(…) should appear. Every other method builds queues by calling it.

java/PQueue.javalines 64–69
/** TODO 2: smart constructor — restore the invariant: if front is
 *  empty, the reversed back must become the front. Build every queue
 *  below only through make, and the invariant holds everywhere. */
private static <T> PQueue<T> make(Node<T> front, Node<T> back) {
    throw new UnsupportedOperationException("TODO 2: make");
}

Two cases, and the branch is on front alone:

  • Front is non-null. Nothing to fix. Construct the pair as it stands — passing the very front reference in, not a rebuilt copy of it.
  • Front is null. The invariant demands the back be null too, so move it: rev(back) becomes the new front and the new back is null. If back was also null this quietly produces an empty queue, which is exactly right — no special case needed.

The tempting wrong version. Reversing unconditionally passes every check in Tests.java and destroys the performance story: every enqueue becomes O(n) and the front is rebuilt on every operation. No test here inspects the representation, so this one is on you. Branch on the front.

05 — todo 3

enqueue(x) — add at the back

One new Node<> and one call. A version longer than a line is probably doing work that belongs to make.

java/PQueue.javalines 71–75
/** TODO 3: a new queue with x at the back, O(1).
 *  Cons onto back; keep front AS IS — shared, not copied. */
public PQueue<T> enqueue(T x) {
    throw new UnsupportedOperationException("TODO 3: enqueue");
}

Put x at the head of back and hand both halves to make. Do not call the constructor yourself: enqueueing onto the empty queue would leave a null front with a one-element back, which is precisely the state the invariant forbids. make is what catches that.

shares

The new queue points into the old one. Both versions stay usable.

var q1 = PQueue.of(1, 2, 3);
var q2 = q1.enqueue(4);

// q2's front IS q1's front —
// the same object, not a copy
q2.front == q1.front   → true

Only one new node and one new PQueue exist after the call. Three elements were reused untouched.

the result is the point

Nothing happens to q1. Ignoring the return value is a silent no-op.

var q1 = PQueue.of(1, 2, 3);
q1.enqueue(4);          // discarded
q1.toList()             → [1, 2, 3]

The persistence tests do exactly this on purpose. In the imperative Queue from the lecture the same line would have changed q1; here it cannot.

The O(1) claim survives the make call: it only reverses when the front is null, and then the invariant says the back was null too, so the list being reversed holds exactly the one element just consed. Constant work, always.

06 — todo 4

dequeue() — take from the front

The one operation that returns two things, because a persistent structure cannot surrender the value by mutating itself. Java has no pairs, so the lab declares one: Dequeued<T>.

java/PQueue.javalines 77–81
/** TODO 4: the front element and the new version, via make.
 *  Throws NoSuchElementException on the empty queue. */
public Dequeued<T> dequeue() {
    throw new UnsupportedOperationException("TODO 4: dequeue");
}

Three moves. Refuse the empty queue with a NoSuchElementException — peek above shows the exact idiom, message and all, and the test checks the exception's type. Otherwise front.head() is the value, and the queue returned is built from the front's tail and the untouched back, passed through make. That call is where the front can run dry and trigger the flip. Wrap the two in a new Dequeued<>(value, rest).

Callers all over the lab write var d = q.dequeue(); d.value(); d.rest(). The record is how the type system says “the value and the new version” in one word — compare ('a * 'a t) option in the OCaml interface, which says the same thing and adds the empty case.

Why the old queue still works afterwards

Nothing in those three moves writes anywhere — nothing can. The node holding the old head is still there, still pointing at the same tail; the new front simply is that tail. That is why the fan-out test can dequeue the same version twice and get the same answer both times, then push the two results in different directions. One present, several futures.

07 — the tests

What each group asks

The runner in Tests.java is hand-rolled: every check runs whatever the others do, and the tally at the end measures progress. A check that reaches a stub's UnsupportedOperationException is reported as todo; any other exception is WRONG.

groupasksif it fails
basicsdoes it work at all?Empty cases and the single-element round trip. Usually the wrong exception type on the empty dequeue, or value and rest swapped.
FIFO contractis it a queue?Order under interleaving, plus 2000 random operations checked against an ArrayDeque. A mismatch means the abstraction function and the implementation disagree.
persistenceis it persistent?Old versions survive an enqueue and a dequeue whose results are deliberately thrown away; the same version dequeued twice yields the same value, and the two futures diverge. These are the tests the lecture is about.

Finishing TODO 1 and TODO 2 alone changes nothing on screen. rev and make are private helpers no test can call. The first visible movement comes with TODO 3, and the round trip needs TODO 4. Work top to bottom and expect the tally to sit still for a while.

08 — run it

The working loop

$ cd java
$ javac *.java && java Tests # after every TODO
# once everything is green — the queue drives a real search:
$ java MazeSolver ../mazes/medium.txt
$ java MazeSolver ../mazes/medium.txt --stack # --dfs: the old name, same search

On mazes/medium.txt the BFS run should report 306 cells explored, path length 75 — the same numbers as the Python and OCaml solvers. Same specification, same search, same answer.

When progress stalls

  • Everything reports todo. Expected — that is the starting state, and TODO 1 and 2 alone move nothing because both helpers are private.
  • javac complains about a missing type argument. Use the diamond: new Node<>(x, back), new PQueue<>(front, back), new Dequeued<>(v, rest).
  • “dequeue empty throws” goes WRONG. The empty queue returned null, or threw something other than NoSuchElementException. Copy peek.
  • Values are right but shifted by one. dequeue rebuilt from front instead of from front.tail().
  • “2000 random ops” goes WRONG at once. enqueue consed onto the front instead of the back, or make reversed the wrong list.
  • StackOverflowError on the large maze. A recursive rev. The comment's suggestion of a loop was not decorative.

Next: java-architecture.html — immutability, spelled out: what each keyword buys in the solver around this class, and what it costs.