I have a method like this-
public List<Apples> returnFruits(String arg1){
List<Apples> fruits = new ArrayList<Apples>();
Apple a = new Apple();
fruits.add(a);
return fruits;
}
I would like to change it, so that I can specify the fruit type from the method call and return that fruit list. So the 2nd statement should dynamically instantiate the list of fruits that I pass. I thought of this-
public List<?> returnFruits(String arg1){
List<T> fruits = new ArrayList<T>();
T t = new T();
fruits.add(t);
return fruits;
}
But don’t know the right way to do it, as you can see.
In the second method, I just return the fruit instead of the list-
public T returnFruit(){
T t = new T();
return t;
}
The fruits that are passed are NOT in the same class hierarchy and are different types.
Thank you.
There are a number of approaches you could take. One is to use
Class<T>as others have suggested. Another would be to create some sort of producer interface, and pass that in:You have different producers for different fruits:
AppleProducer implements FruitProducer<Apple>,OrangeProducer implements FruitProducer<Orange>, etc. This approach just kicks the can a bit — theFruitProducerstill has to create the fruits somehow — but it could be a useful refactoring.Yet another approach relies on the same polymorphism as the
FruitProducerapproach by making the class withreturnFruitsabstract:Now you have different listers:
AppleLister implements FruitLister<Apple>, etc. Each knows how to instantiate the specific classes it needs to return in a list: