#16 · Shared references

Find the bug · #16 · Shared references Medium Java

Opening the leaderboard reorders the members list

After someone opens the leaderboard, the “newest members” list is in alphabetical order too.

On this page

The report

Bug report

The community page shows the newest members in the order they joined, and a leaderboard shows the same people alphabetically. After anyone opens the leaderboard, the newest-members list is alphabetical too.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaClick the line you think is wrong
class Signups {
    private final List<String> names = new ArrayList<>();

    void add(String name) { names.add(name); }

    // The signups in the order people joined.
    List<String> inOrder() { return names; }

    // The same people, alphabetically, for the leaderboard.
    List<String> alphabetical() {
        List<String> sorted = names;
        Collections.sort(sorted);
        return sorted;
    }
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
Signups s = new Signups();
s.add("Ravi");
s.add("Asha");
s.add("Meera");
System.out.println(s.alphabetical());
System.out.println(s.inOrder());

It prints

[Asha, Meera, Ravi]
[Asha, Meera, Ravi]

It should print

[Asha, Meera, Ravi]
[Ravi, Asha, Meera]
Show the answer: the bug, the fix, and how you’d find it

The bug (line 11)

Line 11 makes sorted point to the same list as names, and Collections.sort sorts in place. So sorting for the leaderboard reorders the signups themselves, and the join order is lost for good. Sort a copy: new ArrayList<>(names).

The fix

8 9    // The same people, alphabetically, for the leaderboard.10    List<String> alphabetical() {11        List<String> sorted = names;11        List<String> sorted = new ArrayList<>(names);12        Collections.sort(sorted);13        return sorted;14    }

How you’d find it

  1. Reproduce in the order the report gives: add three names, open the leaderboard, then ask for the join order. It’s alphabetical.
  2. The join order was right before the leaderboard call, so that call changes shared state. It calls Collections.sort, which works in place.
  3. Check what it sorts: sorted is names, the same object. Java assignment never copies a list.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

Signups s = new Signups();
s.add("Ravi");
s.add("Asha");
s.alphabetical();
check(s.inOrder().equals(List.of("Ravi", "Asha")), "join order kept");
check(s.alphabetical().equals(List.of("Asha", "Ravi")), "sorted");

Where else this bites

  • A getter that returns its internal list lets any caller change the object’s state.
  • JavaScript’s array.sort() and Python’s list.sort() are in place too.
Your progress stays on this device.