Question

Say a class is defined like:

public class foodFactory{

    protected EList<food> Basket;

    public List<food> getBasket(){
        return Basket;
    }
}

The following throws exeption when I try to run it:

foodFactory factory = new foodFactory();

ArrayList<food> foodbasket;

foodbasket = (ArrayList<food>)getBasket();

And I'm not seeing why. Did I not cast it properly?

Était-ce utile?

La solution

Well, as long as EList is ot derived from ArrayList, there must be a ClassCastException.

List<food> foodbasket = (List<food>) factory.getBasket();

Don't use ArrayList, use the interface List.

By the way, you should use the java naming conventions.

Classnames start uppercase. Valiables are lowercase.

Autres conseils

Is the factory a nested class? If not, shouldn't you be calling it like this?

foodFactory factory = new foodFactory();

List<food> foodbasket = (ArrayList<food>) factory.getBasket();

On another note, you should be using foodbasket as an EList.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top