[英]How can I remove a specific object from an arrayList and how can I check if it contains this object?
I have an arrayList type shopping cart. 我有一个arrayList类型的购物车。 When I add an new item into the shopping cart, I will check first if the shopping cart already has this item. 当我向购物车中添加新商品时,我将首先检查购物车中是否已有该商品。 But the cart.contains(item) method didn't work, it return false even there is a same item in the cart. 但是cart.contains(item)方法不起作用,即使购物车中有相同的商品,它也会返回false。 The second problem is I was not able to remove this item object from the shopping cart arrayList. 第二个问题是我无法从购物车arrayList中删除此项目对象。 My code shows as below: 我的代码如下所示:
@Controller
@RequestMapping("/addTo.htm")
public class AddToController{
@SuppressWarnings("unchecked")
@RequestMapping(method=RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String action = request.getParameter("action");
System.out.println(action);
ModelAndView mv = new ModelAndView();
ArrayList<Item> cart;
if(session.getAttribute("cart") != null) {
cart = (ArrayList<Item>) session.getAttribute("cart");
}else {
cart = new ArrayList<Item>();
}
if(action.equals("addToCart")) {
long itemId = Long.parseLong(request.getParameter("itemId"));
ItemDAO itemDao = new ItemDAO();
Item item = itemDao.get(itemId);
System.out.println("111"+cart.contains(item));
if (!cart.contains(item)) {
cart.add(item);
}
double total = 0;
int count = 0;
for (Item i : cart) {
total = total + i.getPrice();
count += 1;
}
session.setAttribute("cart", cart);
mv.addObject("total", total);
mv.addObject("count", count);
mv.setViewName("User/viewCart");
}
if(action.equals("remove")){
System.out.println("cart size is" + cart.size());
Long itemId = Long.parseLong(request.getParameter("item"));
ItemDAO itemDao= new ItemDAO();
Item item = itemDao.get(itemId);
System.out.println(cart.contains(item));
session.setAttribute("cart", cart);
System.out.println(cart.size());
}
return mv;
}
}
Can anyone help me solve this problem? 谁能帮我解决这个问题? Thanks!! 谢谢!!
You will need to add a .equals
method to the Item class so ArrayLists know how to compare two different objects together. 您将需要向Item类添加.equals
方法,以便ArrayLists知道如何将两个不同的对象一起比较。 While we are at it we should add a hashCode
method as well. 在此过程中,我们还应该添加一个hashCode
方法。 This is mainly useful for Sets but always good to have it as a backup in case we need it. 这主要对Sets有用,但是在需要时最好将其作为备份。
We can use the .indexOf(Item) method to get the position of an object in the list. 我们可以使用.indexOf(Item)方法获取对象在列表中的位置。 If the number returns if -1. 如果数字返回-1。 Then it's not in the list. 那么它不在列表中。 If it is 0 or greater then it's in there and we can use the index to remove the item. 如果它是0或更大,那么它就在里面,我们可以使用索引来删除该项目。
public class Item{
private String type;
public Item(String type){
this.type = type;
}
public String getType(){
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Item))
return false;
Item other = (Item) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
Now that we have a .equals and hashcode. 现在我们有了一个.equals和hashcode。 We can now compare them in the ArrayList. 现在,我们可以在ArrayList中对其进行比较。
ArrayList<Item> itemList = new ArrayList<Item>();
// Fill the list
itemList.add(new Item("Banana"));
itemList.add(new Item("Toaster"));
itemList.add(new Item("Screw Driver"));
Item item = new Item("Hand Grenade");
itemList.add(item);
int index = itemList.indexOf(item);
if( index != -1 ){
System.out.println("The item is in index " + index);
// Remove the item and store it in a variable
Item removedItem = itemList.remove(index);
System.out.println("We removed " + removedItem.getType() + " from the list.");
}
您必须重写.equals
项的.equals
方法。默认情况下,Java通常将比较对象引用,而不是对象的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.