Let's set up a few hypothetical classes
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Rat extends Animal {
}
How would I go about doing something like this?
List<Animal> listOfAnimals = ArrayList<Animal>();
listOfAnimals.add(new Dog);
listOfAnimals.add(new Cat);
listOfAnimals.add(new Rat);
listOfAnimals.add(new Rat);
//Return a list of animals that are the type of T
public <T> ArrayList<T> animalsOfType(T animal) {
for (Animal A : listOfAnimals) {
if (A instanceof T) {
//The current animal in the list is the type of T
}
}
}
This code would thus let me do this
//Returns a list of all dogs from the current list of animals
List<Dog> currentListOfDogs = animalsOfType(Dog);
I've seen a couple other SO pages referencing this and that it isn't possible, but I don't really understand the workaround that they're suggesting (such as what's referenced here). Is this possible, and how exactly would I have to restructure my classes in order to achieve a result like this?
Thanks in advance!