[英]Casting List<Animal> to List<Dog>
I have an Animal.Class and Dog class which extends Animal.Class 我有一个Animal.Class和Dog类,它扩展了Animal.Class
May I know if there is a quick and easy way to do this? 我可以知道是否有一种快速简便的方法吗?
List<Dog> dogList = getAnimalList();
public List<Animal> getAnimalList(){
List<Animal> animalList = new LinkedList<Animal>();
return animalList;
}
I don't wish to look the entire animal List again unless absolutely necessary. 除非绝对必要,否则我不希望再看整个动物名单。
The dog class just contain an extra boolean value for other checking purpose. dog类只包含一个额外的布尔值以用于其他检查目的。
Generics inheritance is little different than java inheritance principle. 泛型继承与java继承原则略有不同。 You need to use
?
你需要用
?
(wildcards) (通配符)
List<? extends Animal> dogList = getAnimalList();
EDIT: 编辑:
Your question isn't completely clear, so I'll just address what might be your issue. 你的问题并不完全清楚,所以我就解决什么可能是您的问题。
If you have a list of animals, which contains many kinds of animals: 如果你有动物名单,其中包含多种动物:
List<Animal> animals = new ArrayList<>();
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Hippo());
And you want to filter the elements of that list down to a specific subtype, then you need to iterate that list and check/cast to the subtype: 并且您希望将该列表的元素过滤到特定的子类型,然后您需要迭代该列表并检查/强制转换为子类型:
List<Dog> dogs = new ArrayList<>();
for (Animal animal : animals) {
if (animal instanceof Dog) {
dogs.add((Dog)animal);
}
}
This is easier done using Guava : 使用Guava更容易完成:
List<Dog> dogs = Lists.newArrayList(Iterables.filter(animals, Dog.class));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.