简体   繁体   中英

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.

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

尝试

List<? extends A> = getList()

你不能这样做的原因是A和B不一样,你指定getList返回一个B的List(不是超类或子类)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM