简体   繁体   English

Java-从超类的ArrayList中选出子类

[英]Java - Sorting out subclass from ArrayList of superclass

I have an ArrayList which contains objects of the super class and some subclass objects. 我有一个ArrayList,其中包含超类的对象和一些子类的对象。 Let's call them subclass1 and subclass2. 我们称它们为subclass1和subclass2。

Is there a way I can go ArrayList and discern which objects are SuperClass, subclass1 and subclass2. 有没有办法我可以去ArrayList并辨别哪些对象是SuperClass,subclass1和subclass2。 So I can put them into ArrayList and ArrayList. 因此,我可以将它们放入ArrayList和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: 您可以使用instanceof关键字检查所需的类型, instanceof

for (food f : foods)
{
    if (f instanceof pudding)
        puds.add(f);
    else if (f instanceof breakfast)
        wakeupjuices.add(f);
}

This can be solved elegantly with Guava using Multimaps.index : 这可以通过Guava使用Multimaps.index 优雅地解决:

    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);

The output will be a Guava Multimap with three separate entries for: 输出将是带有三个单独条目的Guava Multimap ,用于:

  1. an immutable list with all breakfast instances under key "breakfasts". 一个不可变的列表,其中所有早餐实例均在“早餐”键下。
  2. an immutable list with all pudding instances under key "puddings". 一个不可变的列表,其中所有布丁实例位于键“ puddings”下。
  3. and possibly an immutable list with objects with every food instance that is neither breakfast nor pudding under key "something else". 并且可能是一个不可变的列表,其中包含每个食物实例的对象,这些对象既不是早餐也不是布丁,位于关键“其他”下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM