vendredi 4 décembre 2015

Checking for an instance of a sub class in a list and returning the object

I have two objects A and B. Where B is an extension of A.

and I have a list that can contain As and Bs

and I have a method that goes something like:

B findB()
{
    for (int i = 0; i < ABlist.size(); i++)
    {
        if(ABlist.get(i) instanceof B)
        {
                return ABlist.get(i);
        }
        else{return null;}
    }
    return null;
}

which is supposed to look through all the objects in the list and return the object if it is an instance of B. But im getting an incompatible types error because an A cannot be converted to a B.

How would be the best way to solve this issue?

Aucun commentaire:

Enregistrer un commentaire