Remove the one, or remove position one
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 6. Play this one as a puzzle without the answer.
What is wrong
List has remove(int index) and remove(Object o). With an int literal the compiler picks the index version, so the element at position 1 (the value 1 by coincidence) is removed here, and with other data it removes a different value, or throws IndexOutOfBoundsException.
The fix
How to avoid it next time
When the list holds Integer values, cast or box the argument explicitly to remove by value.
Want the background? Read Autoboxing and wrapper types 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 "Remove the one, or remove position one"?
List has remove(int index) and remove(Object o). With an int literal the compiler picks the index version, so the element at position 1 (the value 1 by coincidence) is removed here, and with other data it removes a different value, or throws IndexOutOfBoundsException. The faulty line is line 6: ids.remove(1);
How do I fix it?
Replace it with: ids.remove(Integer.valueOf(1));. When the list holds Integer values, cast or box the argument explicitly to remove by value.
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.