Java from list <B> to list <a>, where B extends A

Is it possible? if not, why is this not possible in Java?

interface B extends A {} public List<B> getList(); List<A> = getList(); // Type mismatch: cannot convert from List<B> to List<A> 

I think that the topic I'm looking for is โ€œcovariant typesโ€ like here and here , but its muddy and it doesn't solve my problem.

+4
source share
3 answers

Here is an intuitive example of how this can lead to horrific errors:

 interface B extends A {} List<B> blist=new List<B>(); List<A> alist=blist; alist.add(new A()); //should be ok, right? B b = blist.get(0); //fail: even though blist is a List<B>, it now has an A in it 
+6
source

Try

 List<? extends A> = getList() 
+4
source

The reason you cannot do this is because A and B are not the same, you indicated that getList returns a list of B (not a superclass or subclass)

+1
source

All Articles