如何获取列表中特定类型的所有对象? [英] How to get all objects of a specific type in a list?
本文介绍了如何获取列表中特定类型的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有水果清单,其中包含各种水果
实现,例如 Apple
,香蕉
,等等。该列表是必需的,因为其他方法会对列表中的所有水果执行常规操作。
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.
如何获取所有水果列表中没有特定类型的对象?例如所有的苹果?进行instanceof / if-else检查非常丑陋,尤其是在有许多不同的类时。
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.
如何改善以下内容?
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;
}
}
推荐答案
您应该知道-实例是不好的代码实践。
You should know - instance of is bad practice of code.
写.getType(),返回对象的枚举类型怎么样?
What about writing .getType(), returned enum type of object?
这篇关于如何获取列表中特定类型的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文