BackendBench
Coffee
Spot the Bug #112

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.

mediumBoxing and genericsbuggy line: 5

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

List<String> names = new ArrayList<>(); names.add("42");

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

🐞 Play today's puzzleAll 132 bugs← #111#113 →

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 compiles with only a warning. The error appears later, as ClassCastException, at a line that looks correct. The faulty line is line 5: List raw = new ArrayList();

How do I fix it?

Replace it with: List names = new ArrayList<>(); names.add("42");. Never use raw types. Treat unchecked warnings as errors in new code.

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.

More tools you might need