如何在列表中获取特定类型的所有对象?

时间:2013-03-16 18:15:24

标签: java design-patterns instanceof

如果我有一个水果列表,其中包含FruitApple等所有类型的Banana实现。此列表是必要的,因为其他方法对所有水果执行一般操作清单。

如何从列表中获取特定类型的所有对象?比如所有苹果?执行instanceof / if-else检查非常难看,特别是当有很多类不同时。

如何改进以下内容?

class Fruit;
class Apple extends Fruit;
class Banana extends Fruit;

class FruitStore {
    private List<Fruit> fruits;

    public List<Apple> getApples() {
        List<Apple> apples = new ArrayList<Apple>();

        for (Fruit fruit : fruits) {
            if (fruit instanceof Apple) {
                apples.add((Apple) fruit);
            }
        }

        return apples;
    }
}

2 个答案:

答案 0 :(得分:1)

你应该知道 - 实例是代码的不良做法。

如何编写.getType(),返回枚举类型的对象?

答案 1 :(得分:0)

您将方法设为通用:

public <T extends Fruit> List<T> getFruitsByType(Class<T> fType) {
    List<T> list = new ArrayList<T>();
    for (Fruit fruit : fruits) {
        if (fruit.getClass() ==  fType) {
            list.add(fType.cast(fruit));
        }
    }
    return list;
}

使用如下:

FruitStore fs = new FruitStore();
List<Apple> apples = fs.getFruitsByType(Apple.class);
相关问题