【问题标题】:How to get all objects of a specific type in a list?如何获取列表中特定类型的所有对象?
【发布时间】:2013-03-16 18:15:24
【问题描述】:

如果我有一个水果列表,其中包含各种 Fruit 实现,例如 AppleBanana 等。该列表是必要的,因为其他方法对列表中的所有水果执行一般操作。

如何从列表中取出特定类型的所有对象?例如所有的苹果?进行 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;
    }
}

【问题讨论】:

  • instanceof 不是按类型区分对象的明显方式吗?它有效,使用它。
  • 或者,使用访问者模式或其他一些多态性应用来避免必须首先过滤列表。
  • 或者,您可以使用HashMap,其中键作为fruit Type name,值作为ArrayList 的对象fruit
  • 是的 instanceof 有效,但这只是在更复杂的情况下变得混乱的一个示例。
  • @membersound - 您能解释一下为什么需要这种方法吗?也许可以围绕这个需求进行设计

标签: java design-patterns instanceof


【解决方案1】:

您应该知道 - 实例是不好的代码实践。

怎么写.getType(),返回枚举类型的对象?

【讨论】:

  • 这可能比做所有 getclass、instanceof 的东西要好。
【解决方案2】:

你使方法通用:

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);

【讨论】:

    猜你喜欢
    • 2022-08-15
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多