TryBugHunt
javaOtherMedium

Cancelling order 3 crashes the order list

BugFind the bug and fix the code

What it should do

cancelOrder(orderIds, id) removes the order with that ID from the list (if it is there) and returns the list, so cancelOrder([10, 3, 7], 3) returns [10, 7].

What happens instead

cancelOrder([10, 3, 7], 3) throws java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3.

import java.util.*;

public class Main {
    static List<Integer> cancelOrder(List<Integer> orderIds, int id) {
        orderIds.remove(id);
        return orderIds;
    }
}

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 mutation and copying bugs pattern

Two references to one object, so changing one changes both; shallow copies of lists.

What you'll practise

A medium Java debugging exercise about mutation and copying bugs: two references to one object, so changing one changes both; shallow copies of lists.

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)

List has two remove methods: remove(int index) and remove(Object value). Because id is an int, Java picks remove(int index), so the code removes the item at position 3, not the item whose value is 3. For a list of three items that position does not exist, hence the crash. With other inputs it quietly removes the wrong order, which is worse. On a List<Integer>, pass a boxed value to remove by value: remove(Integer.valueOf(id)). Overloads that differ only by int versus Object are a known Java trap, and List.remove is the most common one.

The pattern behind it: mutation and copying bugs.

More mutation and copying bugs to practise

Seen this error in your own code?

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/ab366356-4e27-4a3d-8c48-78662a08ad4b" title="Debugging challenge: Cancelling order 3 crashes the order list" 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/ab366356-4e27-4a3d-8c48-78662a08ad4b">TryBugHunt</a></p>