What's the best way in Java to convert a collection of a subtype to a collection of a supertype ?
class A {}
class B extends A {}
final A a = new B(); // OK.
final Collection<B> bs = Arrays.asList(new B());
final Collection<A> as1 = bs; // <- Error
final Collection<A> as2 = (Collection<A>) (Collection<?>) bs; // <- Unchecked cast warning
final Collection<A> as3 = bs.stream().collect(Collectors.toList()); // Browses through all the elements :-/
I have to implement a method (defined in an interface) that returns a Collection<A>
while the concrete result I get is a Collection<B>
.