How to get all objects of a specific type in a list?

▼魔方 西西 提交于 2019-12-20 03:44:06

问题


If I have a list of fruits, containing all sort of Fruit implementations like Apple, Banana, etc. The list is necessary as other methods perform general actions on all fruits in the list.

How can I get all objects of a specific type out of the list? Eg all apples? Doing instanceof/if-else checks is very ugly, especially when there are lots of classes to differ.

How can the following be improved?

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

回答1:


You should know - instance of is bad practice of code.

What about writing .getType(), returned enum type of object?




回答2:


You make the method generic:

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

And use it as follows:

FruitStore fs = new FruitStore();
List<Apple> apples = fs.getFruitsByType(Apple.class);


来源:https://stackoverflow.com/questions/15452858/how-to-get-all-objects-of-a-specific-type-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!