Search code examples
javalistarraylistinvocationtargetexception

Java - InvocationTargetException when casting List to ArrayList


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?


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.