Java overloaded methods with generics and generic collections

Java overloaded methods with generics and generic collections … here is a solution to the problem.

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);

If 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?

Solution

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 is actually <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.

Related Problems and Solutions