I'm struggling with determining the correct method signature, using generics, for a method which transforms a Collection
of type A into a specified collection of type B. For example, I have an ArrayList
of A, and I want the method to return a LinkedList
of B. So far, I've come up with
<A, B, C extends Collection<B>> C mapCollection(
final Iterable<A> source,
final Class<B> destinationClass,
final Class<C> collectionClass)
But, if I write the following code:
ArrayList<TypeA> listOfA = getList();
LinkedList<TypeB> listOfB = mapCollection(listOfA, TypeB.class, LinkedList.class);
The compiler warns about mapCollection
returning LinkedList
. Apparently, it uses the LinkedList.class
argument to determine the type of C
, instead of seeing that C
extends Collection<B>
?
It gets even more interesting if I do
List<TypeB> = mapCollection(listOfA, TypeB.class, LinkedList.class);
because then, the compiler gives a type mismatch error, cannot convert from ArrayList to List<T>
. Interestingly enough, this only happens in Eclipse, javac
is perfectly happy with this code. Of course, I have to use a @SuppressWarnings("unchecked")
which I'd rather avoid.
Any thoughts on how to fix this? Or is this impossible?