Find the bug · #23 · Types and comparisons Hard Java
Big orders don’t merge
Duplicate order lines are merged when quantities match, and it works in every test but never for bulk orders.
On this page
The report
Duplicate lines in an order are merged when they have the same product and the same quantity. It works in every test, but in production, bulk orders with large quantities never merge.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Orders {
// True if two order lines have the same quantity (used to merge duplicates).
static boolean sameQuantity(Integer a, Integer b) {
return a == b;
}
}Read it, then pick a line.
Integer, with a capital I, is an object. What does == compare for objects? And why would small numbers still work?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
System.out.println(Orders.sameQuantity(5, 5));
System.out.println(Orders.sameQuantity(500, 500));It prints
true false
It should print
true true
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 compares two Integer objects with ==, which checks whether they are the same object. Java keeps one shared Integer object for each value from -128 to 127, so small quantities happen to compare equal. Above 127 each value is a new object, and == is false even for equal numbers. Use Objects.equals, which compares the values and handles null.
The fix
1class Orders {2 // True if two order lines have the same quantity (used to merge duplicates).3 static boolean sameQuantity(Integer a, Integer b) {4 return a == b;4 return Objects.equals(a, b);5 }6}How you’d find it
- Reproduce with the numbers from production, not from the tests: 500 and 500 are “different”. 5 and 5 are the same.
- A cutoff between small and large numbers, for an equality check, points at boxing: these are
Integerobjects, notints. - Confirm the cutoff: 127 compares equal, 128 doesn’t. That’s Java’s Integer cache.
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.
check(Orders.sameQuantity(1000, 1000), "large equal quantities");
check(!Orders.sameQuantity(3, 4), "different quantities");Where else this bites
LongandShorthave the same cache.- Comparing values from a
Map<String, Integer>with==.