简体   繁体   中英

How to convert list of generic subtypes to list of specific subtype?

Suppose class B extends class A and we have

List<? extends A> list1;
List<B> list2;

Is there a way to assign list1 to lsit2 without running through all elements?

List<B> list2 = (List<B>)list1 ;

You will have to deal with compiler warning and possibly ClassCastExceptions when getting Elements from list2 .

Simply put, no.

The reason is that the compiler doesn't have any evidence that the runtime types of the list1 elements will be B (or any subtype of B ). They could be of type C extends A , which could lead to ClassCastException s at Runtime.

However, you can always traverse through the list1 and add all the elements to list2 by doing casts (only if you're confident that the types are compatible, of course). Even though it would work, however, is a sign of a bad design.

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