Emmanuel Omife
Emmanuel Omife

Reputation: 29

how to cast arraylist to a class

I am working on a shopping cart, and am getting an exception that an ArrayList cannot be cast to a ShoppingCart. How do I cast an ArrayList to this class?

Code

ShoppingCart shoppingCart;
shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");
if(shoppingCart == null){
    shoppingCart = new ShoppingCart();
}

I got this error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to business.ShoppingCart

which points to

shoppingCart = (ShoppingCart) session.getAttribute("shoppingCart");

Upvotes: 0

Views: 5257

Answers (1)

AJNeufeld
AJNeufeld

Reputation: 8705

You cannot cast an ArrayList to a class, other than Object, or an interface other than List or Collection.

The best you can do is convert the ArrayList into your ShoppingCart class somehow, like:

ShoppingCart cart = null;
Object cart_object  = session.getAttribute("shoppingCart");
if (cart_object instanceof ArrayList) {
    ArrayList cart_list = (ArrayList) cart_object;
    cart = new ShoppingCart(cart_list);
}

Alternately, you could build a new shopping cart, and add the contents of the list to it:

ShoppingCart cart = new ShoppingCart();
Object cart_object  = session.getAttribute("shoppingCart");
if (cart_object instanceof ArrayList) {
    ArrayList cart_list = (ArrayList) cart_object;
    for(Object item : cart_list) {
        cart.add(item);
    }
}

But exactly how, or what you need to do, depends on the implementation details of your ShoppingCart class.

Upvotes: 1

Related Questions