java 将子类 List 转换为基类 List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10548268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast the sub class List to base class List
提问by RTA
Possible Duplicate:
IsList<Dog>
a subclass ofList<Animal>
? Why aren't Java's generics implicitly polymorphic?
I have a List of class Dogswhich extends Animalsand have a List of the following type.
我有一个类Dogs的列表,它扩展了Animals并有一个以下类型的列表。
ArrayList<Animals> animal = new ArrayList<Animals>();
Now I have another class, Puppy, which extends Dogs.
现在我有另一个类Puppy,它扩展了 Dogs 。
And have a List<Puppy> puppy = new ArrayList<Puppy>();
并有一个 List<Puppy> puppy = new ArrayList<Puppy>();
Now I want to cast list animal
to puppy
. Is it possible to do directly?
现在我想将列表转换animal
为puppy
. 可以直接做吗?
I can do it as below.
我可以这样做。
for (Animals ani: animal){
puppy.add((Puppy) ani)
}
But I want a direct casting solution. Is it possible?
但我想要一个直接铸造解决方案。是否可以?
回答by sebastian
No it will not work directly except you define your first list as:
不,它不会直接工作,除非您将第一个列表定义为:
List<? extends Animals> animal;
then you will be able to do:
那么你将能够做到:
List<Puppy> puppy = new ArrayList<Puppy>();
animal = puppy;
回答by RTA
First you have to define your list in base class as...
首先,您必须将基类中的列表定义为...
public ArrayList<? super Animal> ani;
then cast your base class list in extends class as ...
然后将您的基类列表中的扩展类转换为...
ArrayList<? extends Animal> puppy= new ArrayList<Puppy>();
puppy= (ArrayList<? extends Animal>)ani;
List<Puppy> castPuppy = (List<Puppy>)puppy;//here we case the base class list in to derived class list.
Note: it might through unchecked exception
注意:它可能通过未经检查的异常