TryBugHunt
javaType errorHard

Largest payments list puts a refund on top

BugFind the bug and fix the code

What it should do

amounts are payments in cents; refunds are negative. largestFirst(amounts) returns them sorted from largest to smallest, so largestFirst([300, -50, 120]) returns [300, 120, -50].

What happens instead

largestFirst([1500000000, -1500000000, 20]) returns [20, -1500000000, 1500000000]. Small amounts like [300, -50, 120] sort correctly.

import java.util.*;

public class Main {
    static List<Integer> largestFirst(List<Integer> amounts) {
        List<Integer> sorted = new ArrayList<>(amounts);
        sorted.sort((a, b) -> b - a);
        return sorted;
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the type errors pattern

Integer division, autoboxing surprises, and == comparing references instead of values.

What you'll practise

A hard Java debugging exercise about type errors: integer division, autoboxing surprises, and == comparing references instead of values.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

A comparator only has to return a negative, zero or positive number, so b - a looks like a neat shortcut. But the subtraction is done in int. With a large payment and a large refund, b - a is about 3 billion, which overflows to a negative number, so the comparator reports the opposite order for that pair. The sort then makes decisions from contradictory answers and the result is scrambled, not just reversed. Integer.compare(b, a) compares without subtracting and can never overflow. Never write a comparator as a subtraction unless you are sure the values are small; money, IDs and timestamps often are not.

The pattern behind it: type errors.

More type errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/6878b840-e705-49f4-bbef-741deaeffda4" title="Debugging challenge: Largest payments list puts a refund on top" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/6878b840-e705-49f4-bbef-741deaeffda4">TryBugHunt</a></p>