我有一个ArrayList,它包含超类和一些子类对象的对象。我们称它们为subclass1和subclass2。
有没有办法可以去ArrayList并识别哪些对象是SuperClass,subclass1和subclass2。所以我可以将它们放入ArrayList和ArrayList。
这是一个过于简化的版本,但它展示了我希望做的事情。
public class food{
private String name;
public food(String name){
this.name = name;
}
}
public class pudding extends food{
public pudding(String name){
super(name);
}
}
public class breakfast extends food{
public breakfast(String name){
super(name);
}
}
public static void main(String args[]){
ArrayList<food> foods = new ArrayList();
foods.add(new food("Sausage"));
foods.add(new food("Bacon"));
foods.add(new pudding("cake"));
foods.add(new breakfast("toast"));
foods.add(new pudding("sponge"));
foods.add(new food("Rice"));
foods.add(new breakfast("eggs"));
ArrayList<pudding> puds = new ArrayList();
ArrayList<breakfast> wakeupjuices = new ArrayList();
for(food f : foods){
//if(f is pudding){puds.add(f);}
//else if(f is breakfast){wakeupjuices.add(f);}
}
}
答案 0 :(得分:2)
您可以使用instanceof
关键字检查所需类型:
for (food f : foods)
{
if (f instanceof pudding)
puds.add(f);
else if (f instanceof breakfast)
wakeupjuices.add(f);
}
答案 1 :(得分:0)
使用Multimaps.index可以使用Guava 优雅解决这个问题:
Function<food, String> filterFood = new Function<food, String>() {
@Override
public String apply(food input) {
if (input instanceof pudding) {
return "puddings";
}
if (input.b instanceof breakfast) {
return "breakfasts";
}
return "something else";
}
};
ImmutableListMultimap<String, food> separatedFoods = Multimaps.index(list, filterFood);
输出将是一个Guava Multimap,其中包含三个单独的条目: