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.
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
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
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
How do I fix it?
Replace it with: List
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.