Java 如何在列表中获取特定类型的所有对象?
如果我有一个水果列表,包含所有种类的Java 如何在列表中获取特定类型的所有对象?,java,design-patterns,instanceof,Java,Design Patterns,Instanceof,如果我有一个水果列表,包含所有种类的水果实现,如苹果,香蕉,等等。该列表是必需的,因为其他方法对列表中的所有水果执行常规操作 如何从列表中获取特定类型的所有对象?所有的苹果?执行instanceof/if-else检查非常难看,尤其是当有很多类不同时 如何改进以下方面 class Fruit; class Apple extends Fruit; class Banana extends Fruit; class FruitStore { private List<Fruit&g
水果
实现,如苹果
,香蕉
,等等。该列表是必需的,因为其他方法对列表中的所有水果执行常规操作
如何从列表中获取特定类型的所有对象?所有的苹果?执行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;
}
}
类水果;
苹果类水果;
香蕉类水果;
高级水果店{
私人水果清单;
公共列表getApples(){
List apples=new ArrayList();
用于(水果:水果){
if(苹果的水果实例){
苹果。加入((苹果)水果);
}
}
还苹果;
}
}
您将该方法设置为通用:
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;
}
public List getFruitsByType(类fType){
列表=新的ArrayList();
用于(水果:水果){
if(fruit.getClass()==fType){
添加列表(fType.cast(水果));
}
}
退货清单;
}
并按如下方式使用:
FruitStore fs = new FruitStore();
List<Apple> apples = fs.getFruitsByType(Apple.class);
FruitStore fs=new-FruitStore();
List apples=fs.getFruitsByType(Apple.class);
您应该知道-的实例是错误的代码实践
写.getType(),返回对象的枚举类型怎么样?按类型区分对象的明显方式不是
instanceof
吗?它可以工作,使用它。或者,使用访问者模式或其他多态性应用程序,以避免首先过滤列表。或者,您可以使用HashMap
,其中key作为fruit类型名称
,value作为fruit
的对象的ArrayList
,但这只是一个在更复杂的情况下变得混乱的例子。@membersound-你能解释一下为什么需要这样一种方法吗?也许可以围绕这个需求进行设计,这可能比做所有getclass、instanceof之类的工作要好。