Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a collection of subtype to collection of supertype [duplicate]

Tags:

java

generics

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> .

like image 885
Emmanuel Guiton Avatar asked Nov 06 '25 20:11

Emmanuel Guiton


1 Answers

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);
like image 126
Andy Turner Avatar answered Nov 09 '25 13:11

Andy Turner