Java - Sorting out subclass from ArrayList of superclass

橙三吉。 提交于 2019-12-11 08:59:13

问题


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

}

回答1:


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



回答2:


This can be solved elegantly with Guava using 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:

  1. an immutable list with all breakfast instances under key "breakfasts".
  2. an immutable list with all pudding instances under key "puddings".
  3. and possibly an immutable list with objects with every food instance that is neither breakfast nor pudding under key "something else".


来源:https://stackoverflow.com/questions/28675827/java-sorting-out-subclass-from-arraylist-of-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!