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> .
Easiest way, assuming you don't need to modify the collection through as1:
Collection<A> as1 = Collections.unmodifiableCollection(bs);
If you do need to modify the collection, the only safe thing to do is to copy it:
Collection<A> as1 = new ArrayList<>(bs);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With