2

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

Emmanuel Guiton
  • 1,315
  • 13
  • 24

2 Answers2

2

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);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
-1

Additional suggestion :

public static <A> Collection<A> coerce(final Collection<? extends A> col)
{
    return (Collection<A>) col;
}
Emmanuel Guiton
  • 1,315
  • 13
  • 24