Answers for "how to sort an arraylist by subclases"

0

how to sort an arraylist by subclases

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

}
Posted by: Guest on March-03-2020
0

how to sort an arraylist by subclases

for (food f : foods)
{
    if (f instanceof pudding)
        puds.add(f);
    else if (f instanceof breakfast)
        wakeupjuices.add(f);
}
Posted by: Guest on March-03-2020

Code answers related to "how to sort an arraylist by subclases"

Browse Popular Code Answers by Language