Java Reference
In-Depth Information
For purposes of overload resolution, the signatures of the getData() methods differ
only in the static type of their formal parameters. The OverLoader class inherits from
java.util.HashMap and overrides its get() method to provide the checking function-
ality. This implementation can be extremely confusing to the client who expects both
getData() methodstobehaveinasimilar fashionandnotdependonwhetheranindexof
the record or the value to be retrieved is specified.
Although the client programmer might eventually deduce such behavior, other cases,
such as with the List interface, may go unnoticed, as Joshua Bloch [Bloch 2008] de-
scribes:
The List<E> interface has two overloadings of the remove method: remove(E) and
remove(int) . Prior to release 1.5 when it was “generified,” the List interface had
a remove(Object) method in place of remove(E) , and the corresponding parameter
types, Object and int , were radically different. But in the presence of generics and
autoboxing, the two parameter types are no longer radically different.
Consequently, a programmer may fail to realize that the wrong element has been re-
moved from the list.
Afurtherproblemisthatinthepresenceofautoboxing,addinganewoverloadedmeth-
oddefinitioncanbreakpreviouslyworkingclientcode.Thiscanhappenwhenanewover-
loaded method with a more specific type is added to an API whose methods used less
specific types in earlier versions. For example, if an earlier version of the OverLoader
class provided only the getData(Integer) method, the client could correctly invoke this
method by passing a parameter of type int ; the result would be selected on the basis of
its value because the int parameter would be autoboxed to Integer . Subsequently, when
the getData(int) method is added, the compiler resolves all calls whose parameter is
of type int to invoke the new getData(int) method, thereby changing their semantics
and potentially breaking previously correct code. The compiler is entirely correct in such
cases; the actual problem is an incompatible change to the API.
Compliant Solution (Method)
Naming the two related methods differently eliminates both the overloading and the con-
fusion:
Click here to view code image
public Integer getDataByIndex(int i) {
// No longer overloaded
}
Search WWH ::




Custom Search