Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java cast from List<B> to List<A> where B extends A

is this possible? if not, why isn't this 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 the topic I'm looking for is "covariant types" as here and here, but its murky and it doesn't solve my problem.

like image 277
Dustin Getz Avatar asked Dec 17 '22 08:12

Dustin Getz


2 Answers

Here is an intuitive example of how this can make things go horribly wrong:

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
like image 176
Corey Kosak Avatar answered Dec 24 '22 21:12

Corey Kosak


Try

List<? extends A> = getList()
like image 21
gkamal Avatar answered Dec 24 '22 20:12

gkamal