seesee
seesee

Reputation: 1155

Casting List<Animal> to List<Dog>

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

Answers (2)

kosa
kosa

Reputation: 66657

Generics inheritance is little different than java inheritance principle. You need to use ?(wildcards)

List<? extends Animal> dogList = getAnimalList();

EDIT:

Wildcard Guidelines:

  1. An "in" variable is defined with an upper bounded wildcard, using the extends keyword.
  2. An "out" variable is defined with a lower bounded wildcard, using the super keyword.
  3. In the case where the "in" variable can be accessed using methods defined in the Object class, use an unbounded wildcard.
  4. In the case where the code needs to access the variable as both an "in" and an "out" variable, do not use a wildcard.

Upvotes: 6

Paul Bellora
Paul Bellora

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

Related Questions