Reputation: 6185
Having an interface with these two methods:
void add(T result);
void add(List<T> result);
I was expecting Java on runtime will call the appropriated method:
final U result = getResult();
myInterface.add(result);
If U
is a list I thought second method would be called, but always the first one is called.
Why this behavior? What should be the correct way to achieve that?
Upvotes: 3
Views: 455
Reputation: 73568
It depends on the compile-time type of U
. If U
is unbounded, the compiler can't determine whether it's a List
or a String
or your aunt Hilda.
So the "ungenericized" code becomes:
final Object result = getResult();
myInterface.add(result);
However, if U
is actually <U extends List<?>>
, the compiler can narrow down the possibilities (with your help) and the "ungenericized" code becomes:
final List result = getResult();
myInterface.add(result);
giving you the expected overloaded method call.
Upvotes: 3