Casting List<Animal> to List<Dog>
generics, java
Solution
Generics inheritance is little different than java inheritance principle. You need to use `?`(wildcards)
List<? extends Animal> dogList = getAnimalList();
EDIT:
Wildcard Guidelines:
- An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
- An "out" variable is defined with a lower bounded wildcard, using the super keyword.
- In the case where the "in" variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
- In the case where the code needs to access the variable as both an "in" and an "out" variable, do not use a wildcard.
Problem
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.
Related problems
- Generics : List<? extends Animal> is same as List<Animal>?
- Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
- Any simple way to explain why I cannot do List<Animal> animals = new ArrayList<Dog>()?
- C# - How to convert List<Dog> to List<Animal>, when Dog is a subclass of Animal?