A raw list that accepted a number
A medium Java puzzle in the boxing and generics 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 5. Play this one as a puzzle without the answer.
What is wrong
A raw type switches off generic checking, so adding an Integer to a list that is declared as List<String> compiles with only a warning. The error appears later, as ClassCastException, at a line that looks correct.
The fix
How to avoid it next time
Never use raw types. Treat unchecked warnings as errors in new code.
Want the background? Read Generics in the Java concepts library.
About boxing and generics
Autoboxing, overload resolution and generics erasure change what a line of code means. The Integer cache, List.remove(int) versus remove(Object) and raw types all behave in ways that surprise careful readers.
In code review: Check the static types involved. When an overloaded method takes either a primitive or an object, work out which one the compiler picks.
More puzzles in this family
Frequently asked questions
What is the bug in "A raw list that accepted a number"?
A raw type switches off generic checking, so adding an Integer to a list that is declared as List
How do I fix it?
Replace it with: List
How do I catch boxing and generics in code review?
Check the static types involved. When an overloaded method takes either a primitive or an object, work out which one the compiler picks.
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.