I’m getting a compile error The method getRecommendedIds(String, Object&Comparable<?>&Serializable[]) is ambiguous for the type MyService when trying to call an overloaded method that uses generics and varargs.
The service:
public interface MyService {
public <K> List<K> getRecommendedIds(String datasource, K... ids);
public <K> List<K> getRecommendedIds(String datasource, int limit, K... ids);
}
The call:
@Test(expected = NullPointerException.class)
public void testGetWithLimitThrowsNpeForNullDatasource() {
service.getRecommendedIds(null, 3, UUID.randomUUID());
}
Is there any way around this?
Because the K variable is not bounded the call is indeed ambiguous – it could be a call to the three-argument version, or it could be a call to the
(String, K...)version with the 3 autoboxed as anIntegerandKbound toObject. If you call it aswith an explicit binding for K it will work because neither
intnorIntegeris assignable to theUUIDtype, so the call must be to the three arg version. You could also get away without the explicit bound if you assigned the return value of the call to a variable that restricts the type, i.e.Here the compiler must bind
KtoUUIDto make the return types match.