BackendBench
Coffee
Spot the Bug #102

Ten sorts before nine

A easy Java puzzle in the collections contracts family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

easyCollections contractsbuggy line: 6

Highlighted: line 6. Play this one as a puzzle without the answer.

What is wrong

Strings are ordered lexicographically, character by character, so "10" and "100" sort before "2" and "9". The output is [10, 100, 2, 9], which is not numeric order.

The fix

ids.sort(Comparator.comparingInt(Integer::parseInt));

How to avoid it next time

Sort by the type you mean. Convert to numbers, or store numeric identifiers as numbers.

Want the background? Read The Collections utility class in the Java concepts library.

About collections contracts

Collection classes come with contracts about ordering, mutability and key behavior. Fixed-size lists, views of other collections and mutable map keys break those contracts without compile errors.

In code review: Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #101#103 โ†’

Frequently asked questions

What is the bug in "Ten sorts before nine"?

Strings are ordered lexicographically, character by character, so "10" and "100" sort before "2" and "9". The output is [10, 100, 2, 9], which is not numeric order. The faulty line is line 6: Collections.sort(ids);

How do I fix it?

Replace it with: ids.sort(Comparator.comparingInt(Integer::parseInt));. Sort by the type you mean. Convert to numbers, or store numeric identifiers as numbers.

How do I catch collections contracts in code review?

Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need