问题
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