[英]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
.我正在处理购物车,并且收到一个异常,即ArrayList
无法转换为ShoppingCart
。 How do I cast an ArrayList
to this class?如何将ArrayList
为此类?
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");
You cannot cast an ArrayList
to a class, other than Object
, or an interface other than List
or Collection
.您不能将ArrayList
转换为Object
以外的类或List
或Collection
以外的接口。
The best you can do is convert the ArrayList
into your ShoppingCart
class somehow, like:您能做的最好的事情是以某种方式将ArrayList
转换为您的ShoppingCart
类,例如:
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.但究竟如何或您需要做什么,取决于您的ShoppingCart
类的实现细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.