I’m having a problem getting this type conversion working correctly. My guess is the bounded generic wildcard <? super SomeType> doesn’t work with interface implementations.
// sample class definitions
public interface IFace<T> { ... }
public class MyClass<T1, T2> { ... }
public class UtilityClass<T> {
public List<MyClass<T, ? super IFace<T>>> getList() { ... }
}
public class Actor extends SomeObj implements IFace<TypeA> { ... }
// use...
UtilityClass<TypeA> utility = new UtilityClass<TypeA>();
List<MyClass<TypeA, Actor>> list = utility.getList();
Type mismatch: cannot convert from List<MyClass<TypeA, ? super IFace<TypeA>> to List<MyClass<TypeA, Actor>>
Intuitively, one might try to resolve the issue by making the method generic:
But this syntax isn’t allowed, as it typically doesn’t make sense to give a lower bound to type parameters using
super. See this article for a good explanation of why: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ107Edit:
Looking at your code, I think you may be confusing
superwithextendsin specifying bounds of a type parameter. It would be meaningful ifgetList()returned aList<MyClass<T, ? extends IFace<T>>>instead, as this is specifying an upper bound on the second type parameter ofMyClass(in other words that type must be something implementingIFace<T>).As natix’s answer points out, using wildcards in generic return types is discouraged because it effectively hides part the generic type information for the returned object. Instead, make the method generic:
Which allows the calling code to specify the type of
Xthrough type inferrence.