简体   繁体   English

如何将通用子类型列表转换为特定子类型列表?

[英]How to convert list of generic subtypes to list of specific subtype?

Suppose class B extends class A and we have 假设B类扩展了A类,我们有

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

Is there a way to assign list1 to lsit2 without running through all elements? 有没有一种方法可以在不运行所有元素的情况下将list1分配给lsit2

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

You will have to deal with compiler warning and possibly ClassCastExceptions when getting Elements from list2 . list2获取Elements时,您将不得不处理编译器警告以及可能的ClassCastExceptions

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 ). 其原因是,编译器不具有任何证据表明运行时类型的list1元件将被B (或任何亚型B )。 They could be of type C extends A , which could lead to ClassCastException s at Runtime. 它们的类型可能是C extends A ,这可能会在运行时导致ClassCastException

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). 但是,您始终可以遍历list1并通过强制转换将所有元素添加到list2 (当然,只有在您确信类型兼容的情况下)。 Even though it would work, however, is a sign of a bad design. 即使可以使用,但这也表明设计不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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