Search code examples
javainterfacearraylistsuperclassinstanceof

Iterating through ArrayList and returning an ArrayList of the objects that meet an instanceof check


I'm having a problem with class types. I have a super class "Edible" and an interface "Colorful". Not all edible items are colorful so colorful is only implemented on certain Edible objects. I'm trying to take an ArrayList of Edible items, loop through it, and return a new ArrayList that contains only the colorful ones. The error I'm receiving now is

"The method add(Colorful) in the type ArrayList is not applicable for the arguments (Edible)"

How can I get around this restriction?

private ArrayList<Edible> elist;
private ArrayList<Colorful> clist;

public List<Colorful> getColorfulItems(){
    for(Edible x : elist)
        if(x instanceof Colorful){
            clist.add(x);
        }
    return clist;

    }

Solution

  • You need to typecast your Edible to Colorful: -

    if(x instanceof Colorful){
            clist.add((Colorful)x);
    }
    

    Or, if you want to avoid typecase, declare your ArrayList with WildCard: -

    private ArrayList<? extends Colorful> clist;
    

    By declaring your ArrayList like this, you can add anything that is a subtype of Colorful without typecasting

    Also, you don't need to return your modified list everytime, since your list is declared as instance variable. So the change will be reflected in the list, without returning the list.