I’m using the following code to get the first matching element with the given class (Dog, Cat) from a list of abstract type (Animal). Is there another type safe way to do it?
// get the first matching animal from a list
public <T extends Animal>T get(Class<T> type) {
// get the animals somehow
List<Animal> animals = getList();
for(Animal animal : animals) {
if(type.isInstance(animal)) {
// this casting is safe
return (T)animal;
}
}
// if not found
return null;
}
// both Cat and Dog extends Animal
public void test() {
Dog dog = get(Dog.class); // ok
Cat cat = get(Dog.class); // ok, expected compiler error
}
(Cat and Dog extends Animal)
I would change one thing in your code. Instead of
I would use
The latter will not generate unchecked cast warning.