Reputation: 1155
I have an Animal.Class and Dog class which extends 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.
Upvotes: 3
Views: 1739
Reputation: 66657
Generics inheritance is little different than java inheritance principle. You need to use ?
(wildcards)
List<? extends Animal> dogList = getAnimalList();
EDIT:
Upvotes: 6
Reputation: 55223
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:
List<Dog> dogs = Lists.newArrayList(Iterables.filter(animals, Dog.class));
Upvotes: 1