本文介绍了爪哇 - 从超类ArrayList中挑选出的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含超类的对象和一些子类对象的ArrayList。让我们把他们subclass1和subclass2。
有没有一种方法我可以去ArrayList和辨别哪些对象是父类,subclass1和subclass2。这样我就可以把它们放进ArrayList和ArrayList的。
这是一个过于简化的版本,但它证明什么,我希望做的事。
公共类食品{
私人字符串名称;
公共食品(字符串名称){
this.name =名称;
}
}公共类布丁扩展食品{
公共布丁(字符串名称){
超(名);
}
}公共类早餐食品扩展{
公共早餐(字符串名称){
超(名);
}
}公共静态无效的主要(字符串ARGS []){
ArrayList的<食品GT;食品=新的ArrayList(); foods.add(新的食品(香肠));
foods.add(新的食品(培根));
foods.add(新布丁(蛋糕));
foods.add(新早餐(面包));
foods.add(新布丁(海绵));
foods.add(新的食品(米));
foods.add(新早餐(鸡蛋)); ArrayList的<&布丁GT; PUD的=新的ArrayList();
ArrayList的<早餐和GT; wakeupjuices =新的ArrayList(); 对于(食品F:食品){
//如果(f是布丁){puds.add(F);}
//否则,如果(f是早餐){wakeupjuices.add(F);}
}}
解决方案
您可以检查所需要的类型,如这样,使用的instanceof
关键字:
的(食品F:食品)
{
如果(F的instanceof布丁)
puds.add(F);
否则,如果(F的instanceof早餐)
wakeupjuices.add(F);
}
I have an ArrayList which contains objects of the super class and some subclass objects. Let's call them subclass1 and subclass2.
Is there a way I can go ArrayList and discern which objects are SuperClass, subclass1 and subclass2. So I can put them into ArrayList and ArrayList.
This is an overly simplified version but it demonstrates what I'm hoping to do.
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);}
}
}
解决方案
You can check for the desired types like this, using the instanceof
keyword:
for (food f : foods)
{
if (f instanceof pudding)
puds.add(f);
else if (f instanceof breakfast)
wakeupjuices.add(f);
}
这篇关于爪哇 - 从超类ArrayList中挑选出的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!