Java will consider boxing a primitive type to a wrapper type, but only if it hasn't already considered an overloaded method that doesn't need to box the argument.
The JLS, Section 15.12.2, covers which overload is chosen as follows:
- The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.
(bold emphasis is mine)
- The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.
- The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
The compiler sees no other overload of add
that could possibly match add(Character)
without boxing, so it considers boxing in the second phase and finds its match.
However, the compiler does see an overload of remove
that matches without boxing, remove(int)
, so the char
is widened to an int
. The compiler found its method in the first phase, so the second phase was never considered.
This forces you, as you have figured out, to cast the char
explicitly to a Character
to get the proper method matched.
This happens to be a case where in Java 5, introducing boxing and unboxing causes an ambiguity that didn't exist before that version. If these method names were designed with this in mind, the designers most likely would have used different method names, avoiding overloading and this ambiguity here.