Java overloaded methods with generics and generic collections
Interface with both methods:
void add(T result); void add(List<T> result);
I expect Java to call the appropriate method at runtime:
final U result = getResult(); myInterface.add(result);
U were a list, I think the second method would be called, but the first method would always be called.
Why this behavior? What should be the right way to achieve that goal?
It depends on the compile-time type
of U. If
U is unbounded, the compiler cannot determine whether it is
a List or
String or your Aunt Hilda.
So the “ungeneralized” code becomes:
final Object result = getResult(); myInterface.add(result);
However, if U
<U extends List<?>>, the compiler can narrow the possibilities (with your help) and the “non-generalized” code becomes:
final List result = getResult(); myInterface.add(result);
Provides you with the expected overloaded method calls.