BackendBench
Coffee
Spot the Bug #101

A list of numbers with one element

A medium 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.

mediumCollections contractsbuggy line: 6

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

What is wrong

Arrays.asList works on arrays of objects. An int[] is a single object, so the result is a list with one element, an array, and the type is List<int[]>. contains(90) is false.

The fix

List<Integer> list = Arrays.stream(scores).boxed().toList();

How to avoid it next time

Convert primitive arrays with streams (boxed) or use an Integer[]. Arrays.toString helps printing.

Want the background? Read Arrays and the Arrays utilities 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โ† #100#102 โ†’

Frequently asked questions

What is the bug in "A list of numbers with one element"?

Arrays.asList works on arrays of objects. An int[] is a single object, so the result is a list with one element, an array, and the type is List. contains(90) is false. The faulty line is line 6: List list = Arrays.asList(scores);

How do I fix it?

Replace it with: List list = Arrays.stream(scores).boxed().toList();. Convert primitive arrays with streams (boxed) or use an Integer[]. Arrays.toString helps printing.

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