Video in progress

What does this code print, and why?

List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
list.remove(3);
list.remove(Integer.valueOf(1));
list.remove(Integer.valueOf(3));
System.out.println(list);

It prints [2]. list.remove(3) with an int argument calls remove(int index) and removes the 4 at index 3, while the calls made with Integer.valueOf(...) remove by value.

📖 Answer

List has two remove methods:

  • remove(int index): removes by position;
  • remove(Object o): removes by value, the first match.

When choosing an overload, the compiler first looks for a variant that needs no boxing. 3 is an int, so remove(int) is picked.

Step by step:

  1. [1, 2, 3, 4] → remove(3) removes index 3 → [1, 2, 3]
  2. remove(Integer.valueOf(1)) → [2, 3]
  3. remove(Integer.valueOf(3)) → [2]

In an interview it is easy to read the first line in a hurry as "removes the number 3". Then you get [2, 4], which is wrong.

On prod this mistake usually shows up with List<Long> or List<Integer> of ids: in ids.remove(userId), if userId is an int, it removes an index, not a value, or throws an IndexOutOfBoundsException.