Generic producers and consumers in Java
I have this method to retrieve objects that are instances of a given class:
public class UtilitiesClass {
public static final Collection<Animal> get(Collection<Animal> animals,Class<? extends Animal> clazz) {
// returns the Animals which are an instanceof clazz in animals
}
...
}
To call this method, I can do this:
Collection<Animal> dogs = UtilitiesClass.get(animals,Dog.class);
That's good, but I also want to be able to call this method in the following two ways:
Collection<Animal> dogs = UtilitiesClass.get(animals,Dog.class);
or
Collection<Dog> dogsTyped = UtilitiesClass.get(animals,Dog.class);
I mean, I want to be able to store the results of the method in the dog collection or animal, because dog Class extends animal class
I'm thinking about something like this:
public static final <T> Collection<T> get(Class<T extends Animal> clazz) {
// returns the Animals which are an instanceof clazz
}
But it doesn't work Any tips?
Edit: finally, use @ Rohit Jain to answer. This is the solution when calling the utilitiesclass method:
Collection<? extends Animal> dogsAnimals = UtilitiesClass.get(animals,Dog.class); Collection<Dog> dogs = UtilitiesClass.get(animals,Dog.class);
Solution
Yes, you must make the method universal And when declaring type parameters, you should give limits:
public static final <T extends Animal> Collection<T> get(
Collection<Animal> animals,Class<T> clazz) {
}
However, when you add an animal from an animal set to a new set < T >, you must convert it to clazz type You need the class #isinstance (object) method and the class #cast (object) method
