Java – use generics to return multiple types

I have this method –

public List<Apples> returnFruits(String arg1){
List<Apples> fruits = new ArrayList<Apples>();
Apple a = new Apple();
fruits.add(a);

return fruits;
}

I want to change it so that I can specify the fruit type from the method call and return the fruit list So the second statement should dynamically instantiate the fruit list I passed 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 as you can see, I don't know the right way

In the second method, I just return the fruit instead of the list –

public T returnFruit(){
T t = new T();
return t;
}

The fruits passed are not in the same class hierarchy and are of different types

thank you.

Solution

There are many ways you can do this One is to use class < T > As others say Another way is to create some kind of generator interface and pass it to:

public interface FruitProducer<T> {
    T createFruit(String arg);
}

public <T> List<T> returnFruits(String arg,FruitProducer<? extends T> producer) {
    List<T> list = new ArrayList<T>();
    T fruit = producer.createFruit(arg);
    list.add(fruit);
    return list;
}

You have different producers of different fruits: appleproducer implements fruitproducer < < Apple >, orangeproducer implements fruitproducer < < orange >, etc This approach just kicks the ball - fruit producer still has to create fruit in some way - but it can be a useful refactoring

Another method relies on the same polymorphism as the fruitproducer method by using the returnfruits abstract class:

public abstract class FruitLister<T> {
    public abstract List<T> returnFruits(String arg);
}

Now you have a different Lister: applelister implements fruitlister < < Apple >, etc Everyone knows how to instantiate the specific class it needs to return in the list:

public class AppleLister implements FruitLister<Apple> {
    @Override
    public List<Apple> returnFruits(String arg) {
            List<Apple> list = new ArrayList<Apple>();
            Apple apple = new Apple(arg);
            list.add(apple);
            return list;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>