简体   繁体   中英

Java - Sorting out subclass from ArrayList of superclass

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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