Video in progress

Senior ☕ Core Java

Why does list.remove(1) on a List<Integer> remove the element at index 1 and not the number 1? What traps are there in overload resolution, and how do you avoid them in an API?

The compiler picks an overload in phases: first without boxing and varargs, then with boxing, and last with varargs. remove(int) matches already in the first phase, so remove(Object) never gets its turn. That's why, in an API, it's better to give differently-meaning overloads different names.

📖 Answer

List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(1);                    // [10, 30]: by index
ids.remove(Integer.valueOf(10));  // [30]: by value

In interviews people often get this wrong and say "boxing wins". In fact, by the JLS there are three phases:

  1. only exact match and primitive widening (int to long);
  2. boxing/unboxing is added;
  3. varargs is added.

If a candidate is found in the first phase, it doesn't move on to the next. This was done so that the meaning of old code wouldn't change when autoboxing was added in Java 5.

Other traps:

  • A null argument. With print(String) and print(Object), print(null) picks the most specific type, String. With print(String) and print(Integer), you get "reference to print is ambiguous". Adding a new overload to a library breaks client code this way.
  • Varargs and a primitive array. Arrays.asList(new int[]{1, 2}) is a List<int[]>, with a single element.
  • Erasure. void save(List<User>) and void save(List<Order>) can't be in one class: "name clash: have the same erasure".
  • Functional interfaces. When you pass a lambda to overloads like Supplier and Callable, inferring the exact type gets hard and sometimes a cast is needed. This is why the JDK gave Comparator.comparingInt, mapToLong and others separate names.
  • Overloading is static, overriding is dynamic. An overload is chosen by the compile-time type: Object o = "x"; print(o) calls print(Object).

My rule in API design: overloads with the same number of parameters only if they do the same thing (for example, append(int), append(String)). If the meaning differs, the name differs too: removeAt(int) and remove(E), findById and findByEmail. Error Prone's InconsistentOverloads check helps, and so does asking in code review, "how does this overload behave with null?"